Documente Academic
Documente Profesional
Documente Cultură
Network Programming
Amit Sharma
3/23/2011 Network Programming Rapid Application Development-CS3011 1
Network Programming
Network programming is a branch of computer science which covers the art of writing application programs or software that run on networks. These software are known as Network Programs.
3/23/2011
Network Programming Rapid Application Development-CS3011
Computer Network
In Tanenbaum (Author of many networking books) words Computer Networks can be described as an interconnected collection of autonomous computers. Two computers are said to be interconnected, if they are able to exchange information. By the term autonomous, it is meant that there should not be any master-slave relationship between the computers, that is, all the computers should have the resources to work independently.
3/23/2011
Network Programming Rapid Application Development-CS3011
Network Programs
The main characteristics of network program is that they must use a computer network in anyway as to perform their job. Network Programs do either of one or all of the following Send data across the network. Provide services over a network. Receives data over a network.
3/23/2011
Networking includes
Network programming includes
Reading and writing network sockets Encryption and decryption of data Translating network protocols Sending data packets to other nodes
Lecture - 2
Client Server
Model
Amit Sharma
3/23/2011
Network Programming Rapid Application Development-CS3011
Networking Models
For data communication to take place, a computer runs a program to request a service from another program residing on the destination computer. This is the basic idea behind network programming which means that two computers should connected to the network and act as a service requester or service provider. It is based on, generally, two models Client - Server Model Peer-to-Peer Model From which client-server model is much popular among the network programmers.
3/23/2011
Network Programming Rapid Application Development-CS3011
Response
3/23/2011
Request
Client-Server Mechanism
1
1 2
1. REQUEST: Client initiates a connection, made request for the service to server. 2. RESPONSE: Server accept the request, respond to the client and provide the services to clients. 11 3/23/2011
Network Programming Rapid Application Development-CS3011
12
13
14
Lecture - 3
Functions of TCP
Amit Sharma
3/23/2011
Network Programming Rapid Application Development-CS3011
15
Stream Segmentation
Because the IP protocol only supports transmission of limited size packets, TCP must break the stream into segments for transmission. In order to amortize the cost of transmitting the IP and TCP headers, it is preferable to transmit packets containing the largest possible payload.
3/23/2011
Network Programming Rapid Application Development-CS3011
16
Stream Reassembly
The TCP streams that are transmitted as IP packets may arrive at the destination in different order than the order sent. TCP must be able to handle out-of-order delivery and still reassemble the data in the order transmitted. TCP addresses this problem by counting the number of bytes transmitted in the stream and identifying each of the first stream byte it carries.
3/23/2011
Network Programming Rapid Application Development-CS3011
17
18
20
Sockets
P O R T P O R T
Java programs communicate through a programming abstraction called socket. A socket is one end-point of a two-way communication link between two computers (or programs) running on a network. A socket is bound to a port number so that the TCP layer can identify the application that data isDevelopment-CS3011 to be sent. destined 3/23/2011 21 Rapid Application
Network Programming
Ports
One mechanism that is commonly used by network protocols, and in particular the Internet transport layer protocols, is port addressing. Every network service is associated with one or more ports on one or more IP interfaces of its host device. Typically, integer numbers are used to identify different ports. In order to contact a network service, it is therefore necessary to provide both the IP address of its host, as well as port number it is using.
3/23/2011
Network Programming Rapid Application Development-CS3011
22
Stream Socket
3/23/2011
23
Package java.net
The Java language supports TCP programming through the java.net.Socket and java.net.ServerSocket classes. Java clients connect to TCP servers by creating instances of the java.net.Socket class. Similarly, Java servers listen for java clients by creating java.net.ServerSocket class. Connections are configured through the methods of these two classes. Actual network communications, however, are performed using the java.io package streaming classes.
3/23/2011
Network Programming Rapid Application Development-CS3011
24
Client Program
A client is a network program residing on local computer, who requests for any service to the server. A client program is a finite process which means that it is started by the user and terminates when the service is complete. For example, Web Browser is a network client which requests to the Web Server to read files, view images or download documents or images on the local computer.
3/23/2011
Network Programming Rapid Application Development-CS3011
25
Functioning of Client
SERVER
P O R T
Connection Request
CLIENT
A client opens the communication channel using the IP address of the remote host and the wellknown port address of the specific server computer. After a channel is active, the client sends its request and receives a response. The request-response part may be repeated for several times. At the end, the client closes the communication channel.
3/23/2011
Network Programming Rapid Application Development-CS3011
26
Server Program
A server is a remote computer on a network which provides services to the clients. When it starts, it opens the channel for incoming requests from clients, but it never initiates a service until it is requested to do so. A server program is an infinite process. When it is starts in runs infinitely unless a problem arises. It waits for incoming requests from clients. When a request arrives, it responds to the request either iteratively or concurrently.
3/23/2011
Network Programming Rapid Application Development-CS3011
28
Functioning of Server
SERVER
PO RT P O R T
Communication Channel
P O R T
CLIENT
On server side, if everything goes well, the server accepts the connection. Upon acceptance the sever gets a new socket bound to a different port. It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client. 3/23/2011 29
Network Programming Rapid Application Development-CS3011
The client and server interact according to protocol. Java servers typically use getInputStream() and getOutputStream() to handle socket communication. Either server or client, or both close the socket. The server returns to listening for connection on its designated port. Incoming connection requests are stored by the operating system in a FIFO queue. Those requests will block while the server is handing client interactions. But with Java, network developer can employ a new thread to handle another client in case Network of servicing the client forProgramming or indefinite time. 31 longer 3/23/2011 Rapid Application Development-CS3011
32
33
34
35
3/23/2011
36
Lecture - 4
Amit Sharma
3/23/2011
37
import java.net.*; import java.io.*; public class SimpleClient { public static void main(String[] args) { String host = sap_server; int port = 1234; try { System.out.println(Attempting to connect to TCP service on host + host + and port: + port); Socket s = new Socket(host,port); System.out.println(Connection Established . . .); Network Programming } 3/23/2011 38 Rapid Application Development-CS3011
Example (contd.) catch(UnknownHostException ue) { System.out.println(Trouble: + ue.getMessage()); } catch(IOException ioe) { System.out.println(Trouble: + ioe.getMessage()); } } }
3/23/2011
39
40
41
42
Terminating Socket
The close() method requests asynchronous termination of the socket connection. The close() method will return immediately, even if data written before invocation has not completed transmission. void close() throws IOException;
3/23/2011
43
Example illustrating reading/writing through Socket /* EchoClient implements a client,, that connects to the EchoServer. The EchoServer simply receives data from client and echoes it back. */ import java.net.*; import java.io.*; public class EchoClient { public static void main(String[] args) { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket(sap_server,4444); out = new PrintWriter(echoSocket.getOutputStream(),true);
3/23/2011
Network Programming Rapid Application Development-CS3011
44
Example illustrating reading/writing through Socket in = new BufferedReader(new InputStreamReader (echoSocket.getInputStream()); } catch(UnknownHostException ue) { System.out.println(Trouble: + ue.getMessage()); } catch(IOException ioe) { System.out.println(Trouble: + ioe.getMessage()); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
3/23/2011
45
Example illustrating reading/writing through Socket String userInput; while(!(userInput = stdIn.readLine()).equals(quit)) { out.println(userInput); System.out.println(Echo: + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } }
3/23/2011
46
47
48
Accepting Socket
The main task of server socket is to receive incoming connection requests and generate a java.net.Socket object that encapsulates each request. Incoming connections are queued until the program retrieves them one at a time by invoking the accept() method. The accept() method takes no arguments, and returns the next connection in the queue.
3/23/2011
Network Programming Rapid Application Development-CS3011
49
Example -- SimpleServer.java import java.net.*; import java.io.*; public class SimpleServer { public static void main(String args[]) { ServerSocket server = null; port = 1234; try { System.out.println(Attempting to bind a TCP port + port); server = new ServerSocket(port); } catch(SecurityException se) { System.out.println(Trouble : + se.getMessage()); } catch(IOException ioe) { System.out.println(Trouble : + ioe.getMessage()); } Network Programming
3/23/2011 Rapid Application Development-CS3011 50
Example contd. try { Socket socket = server.accept(); System.out.println(Accepting connection from: + socket.getInetAddress().getHostName()); socket.close(); } catch(SecurityException se) { System.out.println(Trouble : + se.getMessage()); } catch(IOException ioe) { System.out.println(Trouble : + ioe.getMessage()); } } }
3/23/2011
Network Programming Rapid Application Development-CS3011
51
52
Terminating ServerSocket
A server socket may be terminated simply by invoking the no argument close () method. Closing the server socket will not affect connections that have already been returned by an accept () invocation. The signature is as follows void close () throws IO Exception;
3/23/2011
53
import java.net.*; import java.io.*; public class EchoServer { public static void main(String args[]) { Socket clientSocket; ServerSocket serverSocket; int port = 4444; try { //Creating ServerSocket instance serverSocket = new ServerSocket(port); } catch(SecurityException se) { System.out.println(Trouble : + se.getMessage()); } catch(IOException ioe) { System.out.println(Trouble : + ioe.getMessage()); } Network Programming 3/23/2011
Rapid Application Development-CS3011
54
try { //Server is accepting connection clientSocket = serverSocket.accept(); // Initializing I/O streams PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true); BufferedReader in = new BufferedReader(new InputStreamReader (clientSocket.getInputStream())); //Server is ready to start conversation //Initiate conversation with Client String inputLine; do { inputLine = in.readLine(); out.println(Received : + inputLine); }while(!( inputLine.equalsIgnoreCase(quit)));
3/23/2011
55
3/23/2011
56
Lecture - 5
Chat Messenger
3/23/2011
57
3/23/2011
58
Chat Client
3/23/2011
59
import java.net.*; import java.io.*; public class ChatClient { public static void main(String[] args) { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("127.0.0.1",4444); out = new PrintWriter(echoSocket.getOutputStream(),true); in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); }
3/23/2011
Network Programming Rapid Application Development-CS3011
60
} catch(UnknownHostException ue) { System.out.ptintln(Trouble: + ue.getMessage()); } catch(IOException ioe) { System.out.ptintln(Trouble: + ioe.getMessage()); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput;
3/23/2011
61
System.out.println("Received : " + in.readLine()); do{ System.out.print("Send : "); userInput = stdIn.readLine(); out.println(userInput); System.out.println("Received : " + in.readLine()); }while(! (userInput.equalsIgnoreCase("bye"));
out.close(); in.close(); stdIn.close(); echoSocket.close(); } }
3/23/2011
Network Programming Rapid Application Development-CS3011
62
Chat Server
3/23/2011
63
public class ChatServer { public static void main(String args[]) { Socket clientSocket; ServerSocket serverSocket = null; int port = 4444; try { //Creating ServerSocket instance serverSocket = new ServerSocket(port); } catch(SecurityException se) { System.out.println("Trouble : " + se.getMessage()); } catch(IOException ioe) { System.out.println("Trouble : " + ioe.getMessage());
3/23/2011
Network Programming Rapid Application Development-CS3011
}
64
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); //Server is ready to start conversation //Initiate conversation with Client
String inputLine, userInput; out.println("Server is listening on port " + port);
3/23/2011
Network Programming Rapid Application Development-CS3011
65
do { inputLine = in.readLine(); System.out.println("Received : " + inputLine); System.out.print("Send : "); userInput = stdIn.readLine(); out.println(userInput); }while(!(userInput.equalsIgnoreCase("bye"))); //Close all IO streams and sockets in.close(); out.close(); clientSocket.close(); serverSocket.close(); } }
3/23/2011
Network Programming Rapid Application Development-CS3011
66
Assignment
Create a Chat Messenger with GUI using AWT and Event Handling.
3/23/2011
67