Download presentation
Presentation is loading. Please wait.
Published byEdgar Townsend Modified over 8 years ago
1
CHAPTER-3 NETWORKING PROGRAMMING
2
Network represents interconnection of computers & devices either by cable or satellite link where no cable is needed. Client- receives service. Server- provides service. Reuirement for network: Hardware Software protocol
3
Networking Basics TCP/IP suite UDP Port & socket URL
4
The TCP/IP protocol suite ( Internet Protocol Suite) is a collection of protocols that collectively provides the data transport services used on the Internet. They provide a robust and efficient mechanism for moving data between machines across computer networks. The suite is split into five layers TCP/IP Five Layer Model Application Layer - interfaces between application processes and transport layer services on host computer.
5
Transport Layer - determines how to use the network layer to provide a virtual point-to-point connection between source and destination. TCP segments Network/Internet Layer - layer by which data packets are routed from source to destination. Datagrams Data Link Layer - provides data transfer control across the physical layer Physical Layer - the actual physical medium used for the transfer (e.g. cables, Infra red and microwave)
6
IP address It is unique identification number assigned to each computer. Contains four integr numbers in range 0 to 255. Separated by dot. Address mapped to easy remember site name. Like, www.yahoo.com -67.195.160.76www.yahoo.com Mapping service is called DNS(Domain Name Service.)
7
Protocols HTTP (Hyper Text Transfer Protocol) – transfer web pages from one computer to another on internet. FTP (File Transfer Protocol)- download & upload files from & to the server. SMTP (Simple Mail Transfer Protocol)- sending mails on network. POP (Post Office Protocol)- receives mails into mailboxes.
8
UDP Protocol that transfers data in connection less & unreliable manner on network. Does not maintain record of no. Of bits delivered or received on network. During transmission data may be lost. Faster. Utilizes for images, video,audio files transfer over network.
9
Port & Socket Port is 16 bit number to identify a process on machine. Socket is logical connecting point between client & server that allows communication between two hosts over network. Socket contains a port number & IP address. IP address identifies machine & port number identifies process on that machine. A distinct port number is used between 0 to 65535.
10
80- HTTP 109-POP 21-FTp 25-SMTp 23-Telnet for remote login. Java.net package
11
URL Represents address to access some information or resource on interent. Example: http://www.dreamtech.com:80/index.html Protocol:http IP adress or sever name:www.dreamtech.com Port number:80 File resource: index.html
12
TCPUDP Reliability: TCP is connection-oriented protocol. When a file or message send it will get delivered unless connections fails. If connection lost, the server will request the lost part. There is no corruption while transferring a message. Reliability: UDP is connectionless protocol. When you a send a data or message, you don't know if it'll get there, it could get lost on the way. There may be corruption while transferring a message. Ordered: If you send two messages along a connection, one after the other, you know the first message will get there first. You don't have to worry about data arriving in the wrong order. Ordered: If you send two messages out, you don't know what order they'll arrive in i.e. no ordered
13
TCP VS. UDP TCPUDP eavyweight: - when the low level parts of the TCP "stream" arrive in the wrong order, resend requests have to be sent, and all the out of sequence parts have to be put back together, so requires a bit of work to piece together. Lightweight: No ordering of messages, no tracking connections, etc. It's just fire and forget! This means it's a lot quicker, and the network card / OS have to do very little work to translate the data back from the packets. Streaming: Data is read as a "stream," with nothing distinguishing where one packet ends and another begins. There may be multiple packets per read call. Datagrams: Packets are sent individually and are guaranteed to be whole if they arrive. One packet per one read call.
14
Networking Programming import java.io.*; import java.net.*; class Address { public static void main(String args[ ]) throws IOException { //accept name of website from keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15
System.out.print("Enter a website name: "); String site = br.readLine(); try{ //getByName() method accepts site name and returns its IP //Address InetAddress ip = InetAddress.getByName(site); System.out.println("The IP Address is: "+ ip); }catch(UnknownHostException ue) { System.out.println("Website not found"); }
18
URL class import java.net.*; class MyURL { public static void main(String args[ ]) throws Exception { URL obj = new URL("http://dreamtechpress.com/index.html"); System.out.println("Protocol: "+ obj.getProtocol()); System.out.println("Host: "+ obj.getHost()); System.out.println("File: "+ obj.getFile()); System.out.println("Port: "+ obj.getPort()); System.out.println("Path: "+ obj.getPath()); System.out.println("External form: "+ obj.toExternalForm()); }
21
import java.io.*; import java.net.*; import java.util.*; class Details { public static void main(String args[ ]) throws Exception { //pass the site url to URL object URL obj = new URL("http://www.yahoo.com/index.html"); //open a connection with the site on Internet URLConnection conn = obj.openConnection(); //display the date System.out.println("Date: "+ new Date(conn.getDate())); //display the content type whether text or html
22
System.out.println("Content-type: "+ conn.getContentType()); //display expiry date System.out.println("Expiry: "+ conn.getExpiration()); //display last modified date System.out.println("Last modified: "+ new Date(conn.getLastModified())); //display how many bytes the index.html page has
23
int l = conn.getContentLength(); System.out.println("Length of content: "+ l); if(l == 0) { System.out.println("Content not available"); return; } else { int ch; InputStream in = conn.getInputStream(); //display the content of the index.html page while((ch = in.read())!= -1) System.out.print((char)ch); }
24
Output Date: Wed Aug 07 11:00:14 IST 2013 Content-type: text/html;charset=utf-8 Expiry: 0 Last modified: Thu Jan 01 05:30:00 IST 1970 Length of content: -1
25
Yahoo! India //Roundtrip
26
Creating Network Application Creates server that delivers information. Creates client that receives information. Execute client & server program. Remember: Sockets are communication channels, which facilitate inter-process communication. A socket is one end of a two-way communications link between two programs running on the network. When a computer program needs to connect to a local or wide area network such as the Internet,
27
It uses a software component called a socket. The socket opens the network connection for the program, allowing data to be read and written over the network. It is important to note that these sockets are software, not hardware.
28
Steps for ServerSocket 1. Create a ServerSocket object with some port number at server side. ServerSocket ss = new ServerSocket(777); 2. Make server to wait till client accept the connection. Socket s = ss.accept(); 3. Attach output stream to server socket using its getOutputStream() method. It is used by server socket to send data to client. OutputStream obj = s.getOutputStream();
29
4. Take another stream like PrintStream to send data to client. PrintStream ps = new PrintStream(obj); 5. Send data to client using println() method of PritnStream object. ps.println(str); 6. Close the connection ps.close(); ss.close(); s.close();
30
Steps for Client socket 1. Create Socket at client side using Socket class. Socket s = new Socket(“IPaddress", 777); 2. Add InputStream to socket to receive data. InputStream obj = s.getInputStream(); 3. Create BufferedReader object to read data. BufferedReader br = new BufferedReader(new InputStreamReader(obj)); 4. Read data using read() or readLine() method. read() can read single character at a time, while readLine() can read string.
31
str = br.readLine(); 5. Close the connection by closing all streams & sockets. br.close(); s.close();
32
Server1.java import java.io.*; import java.net.*; class Server1 { public static void main(String args[ ]) throws Exception { //Create a server socket with some port number ServerSocket ss = new ServerSocket(777); //let the server wait till a client accepts connection Socket s = ss.accept(); System.out.println("Connection established"); //attach output stream to the server socket
33
OutputStream obj = s.getOutputStream(); //attach print stream to send data to the socket PrintStream ps = new PrintStream(obj); //send 2 strings to the client String str = "Hello client"; ps.println(str); ps.println("Bye"); //close connection by closing the streams and sockets ps.close(); ss.close(); s.close(); }
34
Client1.java mport java.io.*; import java.net.*; class Client1 { public static void main(String args[ ]) throws Exception { //create client socket with same port number Socket s = new Socket("localhost", 777); //to read data coming from server, attach InputStream to the socket InputStream obj = s.getInputStream(); //to read data from the socket into the client, use BufferedReader
35
BufferedReader br = new BufferedReader(new InputStreamReader(obj)); //receive strings String str; while((str = br.readLine()) != null) System.out.println("From server: "+str); //close connection by closing the streams and sockets br.close(); s.close(); }
39
Two way communication import java.io.*; import java.net.*; class Server2 { public static void main(String args[ ]) throws Exception { //Create server socket ServerSocket ss = new ServerSocket(888); //connect it to client socket Socket s = ss.accept(); System.out.println("Connection established"); //to send data to the client PrintStream ps = new PrintStream(s.getOutputStream()); //to read data coming from the client BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //to read data from the key board
40
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in)); while(true) //server executes continuously { String str,str1; //repeat as long as client does not send null string while((str = br.readLine()) != null) //read from client { System.out.println(str); str1 = kb.readLine(); ps.println(str1); //send to client } //close connection
41
ps.close(); br.close(); kb.close(); ss.close(); s.close(); System.exit(0); //terminate application } //end of while }
42
Client2.java import java.io.*; import java.net.*; class Client2 { public static void main(String args[ ]) throws Exception { //Create client socket Socket s = new Socket("localhost", 888); //to send data to the server DataOutputStream dos = new DataOutputStream(s.getOutputStream()); //to read data coming from the server BufferedReader br = new BufferedReader(new
43
InputStreamReader(s.getInputStream())); //to read data from the key board BufferedReader kb = new BufferedReader(new InputStreamReader(System.in)); String str,str1; //repeat as long as exit is not typed at client while(!(str = kb.readLine()).equals("exit")) { dos.writeBytes(str+"\n"); //send to server str1 = br.readLine(); //receive from server System.out.println(str1); }
44
//close connection. dos.close(); br.close(); kb.close(); s.close(); }
48
Retrieve file import java.io.*; import java.net.*; class FileServer { public static void main(String args[ ]) throws Exception { //create server socket ServerSocket ss = new ServerSocket(8888); //make the server wait till a client accepts connection Socket s = ss.accept(); System.out.println("Connection established"); //to accept file name from client BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); //to send file contents to client }
49
DataOutputStream out = new DataOutputStream(s.getOutputStream()); //read the filename from the client String fname = in.readLine(); FileReader fr = null; BufferedReader file = null; boolean flag; //create File class object with filename File f = new File(fname); //test if file exists or not if(f.exists()) flag = true; else flag = false; //if file exists, send "Yes" to client, else send "No" if(flag == true) out.writeBytes("Yes"+"\n"); else out.writeBytes("No"+"\n");
50
if(flag == true) { //attach file to the FileReader to read data fr = new FileReader(fname); //attach FileReader to BufferedReader file = new BufferedReader(fr); String str; //read from BufferedReader and write to DataOutputStream while((str = file.readLine()) != null) { out.writeBytes(str+"\n"); }
51
file.close(); out.close(); in.close(); fr.close(); s.close(); ss.close(); } }
52
myfile.txt
54
UDP UDP transfers datagrams from a process running in source host to other process running in destination host. Each datagram needs destination address. Datagram communication through java.net package classes: DatagramPacket DatagramSocket
55
DatagramPacket is used for creating packets or datagrams. Different datagrams travel through different route, may arrive in any order and their delivery is not guaranteed in UDP. DatagramSocket is used for sending & receiving datagram packets over network. A datagram socket provides an endpoint & methods to send and receive datagram packets over a network.
56
//A server that sends a messages to the client import java.net.*; class UDPServerEx { public static DatagramSocket mySocket; public static byte myBuffer[]=new byte[2000]; public static void serverMethod() throws Exception { int position=0; while(true) { int charData=System.in.read();
57
UDP server switch(charData) { case -1: System.out.println("The execution of the server has been terminated"); return; case '\r':break; case '\n':mySocket.send(new DatagramPacket(myBuffer,position,InetAddress.getLocalHost(),777)); position=0; break; default: myBuffer[position++]=(byte) charData; }
58
UDP client //UDPClient - receives and displays messages sent from the server import java.net.*; class UDPClient { public static DatagramSocket mySocket; public static byte myBuffer[]=new byte[2000]; public static void clientMethod() throws Exception { while(true) { DatagramPacket dataPacket=new DatagramPacket(myBuffer,myBuffer.length);
59
public static void main(String args[]) throws Exception { System.out.println("Please enter some text here"); mySocket=new DatagramSocket(888); serverMethod(); }
60
mySocket.receive(dataPacket); System.out.println("Message Recieved :"); System.out.println(new String(dataPacket.getData(),0,dataPacket.getLength())); } public static void main(String args[]) throws Exception { System.out.println("You need to press CTRL+C in order to quit"); mySocket=new DatagramSocket(777); clientMethod(); }
62
Content Handler & Protocol Handler Content handler is java object for parsing the content of web page and showing it in web browser window, at client side. Every new web page type, such as Portable Network Graphics (PNG) format, jpg, doc, audio, is associated with content handler. All content handler extends java.net.Content Handler class. Content hadler is invoked through getContent() method of URLConnection class.
63
The job of content handler to read data provided by protocol handler. Protocol handlers are responsible for how data arrives at host. Suppose data delivered from network in compressed form, it is responsibility of protocol handler to unpack data before providing it to content handler.
64
try{ URL u= new URL(http://web/Hi.jpg);http://web/Hi.jpg Image i= (Image)u.getContent(); } Catch(Exception e) { e.printStackTrace(); }
65
In code from Url string firsat we find protocol used. Here it is HTTP, so HTTP protocol handler is responsible for opening the connection with host & transmitting requested data. After connection establishing, protocol handler finds requested file Multipurpose Internet Mail Extension (MIME) type. Protocol handler considers file extension which is.jpg here.
66
Then content handler is responsible for MIME type invocation & then required object I constucted. Here it returns Image type object, which is returned by getContent() method.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.