+ All Categories
Home > Documents > Java TCP Programming

Java TCP Programming

Date post: 18-Nov-2014
Category:
Upload: anik
View: 122 times
Download: 0 times
Share this document with a friend
Description:
Java Socket Programming by my teacher
Popular Tags:
55
Network Programming
Transcript
Page 1: Java TCP Programming

NetworkProgramming

Page 2: Java TCP Programming

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.

Page 3: Java TCP Programming

Computer NetworkIn 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”.

Page 4: Java TCP Programming

Network Programs

Send data across the network.

Provide services over a network.

Receives data over a network.

Invoke services across a network.

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 –

Page 5: Java TCP Programming

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 dataAnd many more . . .

Page 6: Java TCP Programming

What Network Programs can doNetworking 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 And many more . . .

Page 7: Java TCP Programming

Client – Server Model

Page 8: Java TCP Programming

Networking ModelsFor 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 ModelPeer-to-Peer ModelFrom which client-server model is much popular

among the network programmers.

Page 9: Java TCP Programming

Client – Server Model

to whom the request is made, performs the job for the requesting computer. This is the basic idea of 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

Page 10: Java TCP Programming

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.

Request

Response

Page 11: Java TCP Programming

Client-Server Mechanism

11

2 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.

Page 12: Java TCP Programming

Java TCP

Programming

Page 13: Java TCP Programming

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 bi-directional 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.

Page 14: Java TCP Programming

Transmission Control Protocol

• Once the message arrived at the correct IP address, TCP’s 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.

Page 15: Java TCP Programming

Functions of

TCP

Page 16: Java TCP Programming

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 reduce the cost of transmitting the IP and TCP headers, it is preferable to transmit packets containing the largest possible payload.

Page 17: Java TCP Programming

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.

Page 18: Java TCP Programming

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 receiver’s 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.

Page 19: Java TCP Programming

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 payload’s summary is computed and stored in the packet’s 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 multiple bit errors.   

Page 20: Java TCP Programming

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.

Page 21: Java TCP Programming

Sockets

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 is destined to be sent.

PORT

PORT

Page 22: Java TCP 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.

Page 23: Java TCP Programming

Stream Socket

Page 24: Java TCP Programming

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.

Page 25: Java TCP Programming

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.

Page 26: Java TCP Programming

Functioning of Client

A client opens the communication channel using the IP address of the remote host and the well-known 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.

SERVER CLIENTConnection

Request

PORT

Page 27: Java TCP Programming

Structure of Client ProgramClient 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.

Finally the server, the client or both close the sockets.

Page 28: Java TCP Programming

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.

Page 29: Java TCP Programming

Functioning of Server

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.

SERVER CLIENTCommunication

Channel

PORT

PORT

P O R T

Page 30: Java TCP Programming

Structure of Server ProgramThe basic steps for the coding of server program in Java are Instance of server socket is created with listens on selected

for 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” sockets comes from the same Java class, Socket class.

Page 31: Java TCP Programming

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 of servicing the client for longer or indefinite time.

Page 32: Java TCP Programming

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.

Page 33: Java TCP Programming

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.

Page 34: Java TCP Programming

Creating a Client Socket

Although the signature of the constructors only declares the java.net.IOException, users can determine the reason programmatically using following subclasses of java.io.IOException.

• java.net.NoRouteToHostException

• java.net.ConnectException

• java.lang.SecurityException

Page 35: Java TCP Programming

Creating a Client SocketAnother 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.

Page 36: Java TCP Programming

Creating a Client Socket

There is another equivalent constructor with the previous constructor, which is much more convenient –

Socket(InetAddress.getByName(host),port);

Page 37: Java TCP Programming

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.ptintln(“Connection Established . . .“);

   }

       

Page 38: Java TCP Programming

Example (contd.)

        catch(UnknownHostException ue) {

            System.out.ptintln(“Trouble: “ + ue.getMessage());

       }

        catch(IOException ioe) {

               System.out.ptintln(“Trouble: “ + ioe.getMessage());

       }

        catch(SecurityException se) {

              System.out.ptintln(“Trouble: “ + se.getMessage());

       }

   }

}

Page 39: Java TCP Programming

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

Page 40: Java TCP Programming

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.

Page 41: Java TCP Programming

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;

Page 42: Java TCP Programming

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;

Page 43: Java TCP Programming

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”,7);

            out = new PrintWrite(echoSocket.getOutputStream(),true);

    

Page 44: Java TCP Programming

Example illustrating reading/writing through Socket in = new BufferedReader(new InputStreamReader 

                                                 (echoSocket.getInputStream());

     } catch(UnknownHostException ue) {

            System.out.ptintln(“Trouble: “ + ue.getMessage());

     } catch(IOException ioe) {

             System.out.ptintln(“Trouble: “ + ioe.getMessage());

     } catch(SecurityException se) {

             System.out.ptintln(“Trouble: “ + se.getMessage());

     }

     BufferedReader stdIn = new BufferedReader(new

InputStreamReader(system.in));

     

Page 45: Java TCP Programming

Example illustrating reading/writing through Socket      String userInput;

      while(!(userInput = stdIn.readLine()).equals(“quit”)) {

                  out.println(userInput);

                  System.out.println(“Echo: “ + in.readLine(0);

        }

         out.close();

         in.close();

         stdIn.close();

         echoSocket.close();

   }

}

Page 46: Java TCP Programming

Server Side TCP ProgrammingIn 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.

Page 47: Java TCP Programming

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.

Page 48: Java TCP Programming

Accepting SocketThe 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.

Page 49: Java TCP Programming

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());

       }     

Page 50: Java TCP Programming

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());

      }

  }

}

Page 51: Java TCP Programming

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.

Page 52: Java TCP Programming

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;

Page 53: Java TCP Programming

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());

        }

     

Page 54: Java TCP Programming

try {

         //Server is accepting connection

         clientSocket = serverSocket.accept();

         // Initializing I/O streams  

         PrintWriter out = new PrintWriter(s.getOutputStream(),true);

         BufferedReader in = new BufferedReader(new InputStreamReader (clientSocket.getInputStream()));

         //Server is ready to start conversation 

         //Initiate conversation with Client

         String inputLine;

         boolean finished = true;

         do {

                   inputLine = in.ReadLine();

                   if(inputLine.equalsIgnoreCase(“quit”))

                        finished = true;

                   out.println(“Received : “ + inputLine());

                   out.flush();

           }while(!finished); 

   

Page 55: Java TCP Programming

      //Close all IO streams and sockets

in.close();    

out.close();

clientSocket.close();

serverSocket.close();

  } catch(SecurityException se) { 

  System.out.println(“Trouble : ” + se.getMessage());

  } catch(IOException ioe) {

  System.out.println(“Trouble : ” + ioe.getMessage());

  }

 }

}

   


Recommended