You are on page 1of 67

Lecture - 1

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

Invoke services across a network.


Network Programming Rapid Application Development-CS3011

Networking includes
Network programming includes
Reading and writing network sockets Encryption and decryption of data Translating network protocols Sending data packets to other nodes

Providing security to the data


And many more . . .
3/23/2011
Network Programming Rapid Application Development-CS3011

What Network Programs can do


Networking extends the power of a single computer. Network lets one computer communicate with thousands, even millions, of other computers. Network may prove very efficient in the area of Electronic mail Application Services Information sharing Parallel computing Messaging services Website programming 3/23/2011 many more . . . Network Programming And 6
Rapid Application Development-CS3011

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

Client Server Model


In a network if any host wishes to receive a service from a remote computer, it executes specific program to perform the specific job. Then the computer to whom the request is made, performs the job for the requesting computer. This is the basic idea of Client-Server Model.
3/23/2011
Network Programming Rapid Application Development-CS3011

Server and Clients


Client computers are those who made requests. Server computer respond the clients and perform the job requested by the client. client-server programming requires experience with many different technical skills like, database programming, network protocols, user interface design, transaction processing, RPCs, etc. 10 Network Programming

Response

3/23/2011

Request

Rapid Application Development-CS3011

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

Java TCP Programming


Amit Sharma
3/23/2011
Network Programming Rapid Application Development-CS3011

12

Transmission Control Protocol


The TCP is a transport layer protocol. TCP provides reliable, full-duplex connections and reliable service by ensuring that data is resubmitted when transmission results in an error. TCP enables two network entities to establish a bidirectional communications channel for reading and writing streams, that is, sequence of bytes. The TCP protocol guarantees that bytes will be delivered to recipient in the order written by the sender.
3/23/2011
Network Programming Rapid Application Development-CS3011

13

Transmission Control Protocol


Once the message arrived at the correct IP address, TCPs main task is error checking. TCP performs congestion control by controlling the rate with which data is written to the network in response to network conditions. TCP performs an additional service called flow control.
3/23/2011
Network Programming Rapid Application Development-CS3011

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

Handling Packet loss


IP packets carrying segments of the stream may be lost in the way. TCP must be able to detect the fact that a packet has been lost and arrange retransmission. TCP deletes packets loss by positive receiver acknowledgements. When a TCP packet arrives, the receivers TCP protocol implementation will send a TCP packet to the sender acknowledging receipt. If the sender fails to receive acknowledgement by a certain deadline, it will retransmit the packet.
3/23/2011
Network Programming Rapid Application Development-CS3011

18

Data Corruption Detection


The IP protocol only protects its own header and does not make any guarantees on the payload contents. It is therefore possible that one or more bits in the payload may be corrupted due to transmission error. For this payloads summary is computed and stored in the packets header. The receiver of the packet then independently computes the summary of the data received, using the same algorithm and compares it to summary stored in header. This algorithm protects against all 1-bit errors and some Network 3/23/2011 19 multiple bit errors. Application Programming Rapid Development-CS3011

Java TCP Programming


The programming model of TCP communication in Java, rely completely on the sockets and ports. Because TCP is a stream protocol, it allows to send arbitrary amount of data rather rely on class to encapsulate data within TCP packets.
3/23/2011
Network Programming Rapid Application Development-CS3011

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

Network Programming Rapid Application Development-CS3011

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

Structure of Client Program


Client program use TCP/IP sockets for communication with server. The structure of basic client program is A new socket instance is created using a constructor of Socket class. The socket attempts to connect to a remote host, passing and IP address (or URL) and a port number. Socket socket = new Socket(sap_server,1234); Where sap_server is the URL and 1234 is port number where it listens. Once the client connects, the client and server interact according to protocol.
Network Programming Finally the server, the client or both close the sockets. 27 3/23/2011 Rapid Application Development-CS3011

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

Structure of Server Program


The basic steps for the coding of server program in Java are Instance of server socket is created which listens on selected port number, using the constructors of ServerSocket class. ServerSocket serverSocket = new ServerSocket(1234); The above code will create a serverSocket which would listen on port number 1234. This instance listens for connection on the desired port. It waits for client until it attempts to connect. It uses accept() method to establish the connection. Once a client connects, the accept() method returns an instance of the socket class, which it uses as a receiving socket. Client "sending" sockets and servers receiving Network Programming 3/23/2011 Rapid Application Development-CS3011 sockets comes from the same Java class, Socket class. 30

Structure of Server Program


(Contd.)

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

Creating a Client Program


The java.net.Socket of a java.net package implements client side of a two-way connection between Java program and another program on the network. By using this class instead of relying on native code, Java program can communicate over network in platform independent fashion.
3/23/2011
Network Programming Rapid Application Development-CS3011

32

Creating a Client Socket


The java.net.Socket class provides a constructor, which takes an IP address and port number and attempts to establish a connection.

The signature of this constructor is Socket(InetAddress, int port) throws IOException;


Throwing the java.io.IOException exception signals communication error.
3/23/2011
Network Programming Rapid Application Development-CS3011

33

Creating a Client Socket


Although the signature of the constructors only declares the java.io.IOException, users can determine the reason programmatically using following subclasses of java.io.IOException. java.net.NoRouteToHostException java.net.ConnectException
3/23/2011
Network Programming Rapid Application Development-CS3011

34

Creating a Client Socket


Another constructor is provided for use with host names, or IP addresses represented as Strings. The signature is Socket(String host,int port) throws IOException; This constructor may also throw an additional IOException subclass called java.net.UnknownHostException if the host name can not be resolved, or string representation of the IP address is invalid.
3/23/2011
Network Programming Rapid Application Development-CS3011

35

Creating a Client Socket


There is another equivalent constructor with the previous constructor, which is much more convenient Socket(InetAddress.getByName(host),port);

3/23/2011

Network Programming Rapid Application Development-CS3011

36

Lecture - 4

Creating Client and Server Socket

Amit Sharma
3/23/2011

Network Programming Rapid Application Development-CS3011

37

Example demonstrating Socket Creation

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

Network Programming Rapid Application Development-CS3011

39

Reading / Writing Socket


The Socket class provides two methods, one for obtaining an input stream for reading bytes and one for obtaining an output stream for writing byte-stream to the output stream. The streams are represented as java.io.InputStream java.io.OutputStream
3/23/2011
Network Programming Rapid Application Development-CS3011

40

Reading / Writing Socket


An exception java.io.IOException will be thrown in this case. The signatures are java.io.InputStream getInputStream() throws IOException; java.io.OutputStream getOutputStream() throws IOException; Once the input and output streams for the socket have been obtained, it is up to application to determine the contents of communication.
3/23/2011
Network Programming Rapid Application Development-CS3011

41

Getting Socket Information


Connection oriented sockets may be characterized by set: <local_address, local_port, remote_address, remote_port> The four methods for querying the Socket are
InetAddress getInetAddress() throws IOException; int getPort() throws IOException; InetAddress getLocalAddress() throws IOException; int getLocalPort() throws IOException;
3/23/2011
Network Programming Rapid Application Development-CS3011

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

Network Programming Rapid Application Development-CS3011

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

Network Programming Rapid Application Development-CS3011

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

Network Programming Rapid Application Development-CS3011

46

Server Side TCP Programming


In order to accept network connections a Java program must create an instance of java.net.ServerSocket. Server sockets are not directly used to perform any network communication. Instead, they act as factories that create a java.net.Socket object for every incoming TCP communication request. Programs create the server socket, bind to a specific port on one or more interfaces, and then invoke the blocking accept() method.
3/23/2011
Network Programming Rapid Application Development-CS3011

47

Creating Server Socket


The basic ServerSocket constructor takes a single argument, the TCP port number used in binding. The constructor may fail due to an I/O error, or due to a security error. The signature of the constructor is ServerSocket(int port) throws IOException,SecurityException; Port is not permitted to listen more than one process at the same point of time.
3/23/2011
Network Programming Rapid Application Development-CS3011

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

Getting ServerSocket Info


Server socket objects have two identifying attributes: the port number and the InetAddress they are bound to. The java.net.ServerSocket class provides methods to query two values The getInetAddress() method returns the IP address of the interface to which the server socket is bound. The getLocalPort() returns the port the server socket is bound to.
3/23/2011
Network Programming Rapid Application Development-CS3011

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

Network Programming Rapid Application Development-CS3011

53

Example the server side of the Echo Client

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

Network Programming Rapid Application Development-CS3011

55

//Close all IO streams and sockets

in.close(); out.close(); clientSocket.close(); serverSocket.close(); } catch(IOException ioe) { System.out.println(Trouble : + ioe.getMessage()); } } }

3/23/2011

Network Programming Rapid Application Development-CS3011

56

Lecture - 5

Application of Network Programming

Chat Messenger

3/23/2011

Network Programming Rapid Application Development-CS3011

57

3/23/2011

Network Programming Rapid Application Development-CS3011

58

Chat Client

3/23/2011

Network Programming Rapid Application Development-CS3011

59

Example illustrating ChatClient through Socket Programming

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

Example illustrating ChatClient through Socket Programming

} 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

Network Programming Rapid Application Development-CS3011

61

Example illustrating ChatClient through Socket Programming

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

Network Programming Rapid Application Development-CS3011

63

//Example illustrating ChatServer through Socket Programming

import java.net.*; import java.io.*;

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

//Example illustrating ChatServer through Socket Programming

//Server is accepting connection clientSocket = serverSocket.accept();


// Initializing I/O streams PrintWriter out = new PrintWriter(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

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

//Example illustrating ChatServer through Socket Programming

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

Network Programming Rapid Application Development-CS3011

67