Socket Programming

Share Embed Donate


Short Description

Explanation of creating a socket and other brief topics...

Description

[1]

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. This section includes following topics – v Introduction to TCP v Functions of TCP v Java TCP Programming v Sockets v Ports v Package java.net v Client-Side TCP Programming Ø Creating a Socket Ø Reading – Writing Socket Ø Getting Socket Information Ø Terminating Socket v Server-Side TCP Programming Ø Creating ServerSocket Ø Accepting ServerSocket Ø Getting ServerSocket Information Ø Terminating ServerSocket

Transmission Control Protocol The Transmission Control Protocol (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. For example, a Web Browser will communicate with a Web Server over a TCP in order to send a request for a particular page and receive the content of that page. The TCP protocol guarantees that bytes will be delivered to recipient in the order written by the sender. The structure and meaning of the bytes exchanges is typically defined by an application-layer protocol – HTTP – the Hyper Text Transfer Protocol. Once the message arrived at the correct IP address, TCP’s main task is error checking to make sure that the information received by the computer on a TCP/IP network is exactly the same information that was sent to it by another computer on the network. In addition to providing reliable full-duplex channels, TCP also performs an important Internet “community” service. In most networks, the collective maximum rate in which

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[2]

network participants can send data into the shared network generally exceeds the network’s bandwidth. This problem is known as network congestion. It is therefore important to provide some mechanism to control the congestion. TCP performs congestion control by controlling the rate with which data is written to the network in response to network conditions. The distributed algorithm used guarantee that competing TCP streams will get a “fair share” of the network bandwidth. TCP performs an additional service called flow control. In any stream based communication, it is possible for one side to send data at a rate that exceeds the receiver’s capability to process that data. This is different from congestion control because it involves limitation in the receiver’s capability rather than network’s capability. The TCP protocol performs flow control by allowing the receiving end of each unidirectional channel to control the rate in which the sender writes data.

Functions of TCP The main issues that TCP must address are – Ø

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.

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

Throughput Efficiency – The design of a reliable streaming channel is further complicated by the requirement for efficiency. For this one could develop a stop and wait design in which the sender transmits the next packet of data in which the sender transmits the next packet of data every, certain-milliseconds until an Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[3]

acknowledgement is received. But in this design the maximum throughput is limited by the communication round-trip overhead. TCP addresses this problem by using a technique called sliding-window. In this approach, the receiver instructs the sender on the maximum number of unacknowledged bytes that can be transmitted (the window). Once the sender has transmitted a window-size full of data, he must wait for a receiver acknowledgement. When it has been received, the sender can send out as much data as was acknowledged. This mechanism increases the concurrency of operation as well as enables receivers to the control the flow of transmission.

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. 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. Mostly, applications do not care how data is actually transmitted in the network. Applications identify the address of the peer entity and then use sockets interface to read and write data from and to the peer. Sockets include the implementation of network and transport layer protocols providing applications with a simple read/write interface. Because sockets are just programming abstractions for network protocols, the other side of the connection does not have to use them. Sockets don’t use any additional communication mechanism other than that provided by the encapsulated protocol. The socket abstraction was developed in the first networked version of UNIX developed at the University of California at Berkeley by Bill Joy. Those sockets are therefore, also known as Berkeley sockets. Traditionally, sockets abstraction as a core language library feature in order to support portable, cross-platform network programming. The java.net package in the Java API provides a class Socket, that implements one side of two-way connection between one Java program and another program on the network. The Socket class sits on top of a platform-dependent implementation, hiding the details of any particular system from the Java program. By using the java.net.Socket class instead of relying on native code, Java programs can communicate over a network in a platformindependent fashion. Additionally, java.net includes the ServerSocket class, which implements a socket that servers can use to listen for accept connections to clients.

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[4]

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. Now the question arises, how can we find out the port number of a service? The Internet answer to this question is that there is no such directory having port numbers. Instead, published protocols are assigned what are called “well-known port numbers”. The advantage of this solution is that an additional port-directory mechanism is not needed. Every standard Internet application requests a port number from the Internet Assigned Numbers Authority (IANA). For example, tcp:23 port number is assigned for FTP, tcp:80 for HTTP, etc. IANA reserves ports 1 – 1023 for well-known services. Less popular or platform-specific services can still request registration of ports in the range of 1024 – 49151. if a service is meant for Internet deployment, then users can just pick up a port number that is not already assigned. Both the client and server must then be configured to connect to ands bind to the given port. Finally, ports in the range 4915 – 65535 are typically used for ephermal port assignment. Stream Sockets 9. Get input and output stream

11. “3.50 Please”

Java

10. “latte with skim please”

Java 6. Return

Client

Server

accept () 3. Create

8. Get input/output 1. Create

(“server”

stream

7. TCP protocol

TCP

(4567)

Socket 5. Create

TCP

4. TCP connect TCP

Socket

Figure: Use of Sockets to establish two-way communication Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[5]

The diagram illustrates the use of sockets to establish two-way byte-streaming communication. On the left hand side of diagram is a Java-client program wishing to connect to the server on the right. In order to receive remote connections, the server program must first create a ServerSocket. A server is a receiver of incoming connection requests. Each protocol has its own server socket type. For a TCP communication following steps are involved – Ø The server program creates a TCP server socket bound to port 4567. Ø At this point the server invokes the accept() method on the server socket and blocks waiting for the first client connection. Ø

On the right side of the diagram, a Java client program creates a regular socket with the same name or address of the server host as well as the port number of the server program. This protocol type of client socket must match the protocol type of the server.

Ø Upon creation, the socket object attempts to establish communication with its peer using the TCP protocol. Ø Once the TCP handshake is complete, the server socket creates a socket to model the server’s side of the TCP communication. Ø This is returned as the result of the blocked accept() call. At this point, the client and the server are each in possession of a socket object and in bidirectional link. Now in order to transmit information, both the client and the server must obtain an input and output stream from the socket object (steps 8 and 9).

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. The diagram below illustrates the main operations of the Java streaming socket classes. The Java TCP server, on the right, accepts TCP connections by creating a java.net.ServerSocket instance bound to a particular port. When a ServerSocket establishes a connection with a TCP client, it creates a java.net.Socket instance encapsulating that connection and returns it to the server program. The java.net.Socket object returned is bound to an ephermal port number that is different from the one the ServerSocket is listening to. The server retrieves the socket’s input and output streams and effects communication by implementing some protocol.

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[6]

TCP connect

java.net.ServerSocket create(port)

Java

create

Client

(server, port)

java.net.

java.net. TCP

java.io.InputStream

return

Java

to

Server

java.io.OutputStream

java.io.OutputStream

java.io.InputStream

Figure: Main operations of Java Streaming Classes On the client side, TCP connections are established through instances of java.net.Socket associated with a TCP server on the given host and port. Once the client Socket has established a TCP connection, retrieves the socket’s input and output stream, effects communication.

Client-Side TCP Programming 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. Creating a Socket In order to establish a connection with a network server one must have the address of the server’s host, and port number to which the server is bound. 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 as follows – Socket(InetAddress, int port) throws IOException; The constructor returns only after the connection has been established, that is, once the TCP three-way handshake has been completed. Hence the constructor must signal errors in establishing the connection. Throwing the java.io.IOException exception signals such communication error. A connection attempt may fail for multiple reasons. For example, either the remote IP address may not reachable or IP address may be reachable but server may not be bound to the specific port number on the given address. Although the signature of the constructors only declares Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[7]

the java.net.IOException, users wishing to programmatically determine the reason for the connection failure, can try to catch the following java.io.IOException subclasses – Ø java.net.NoRouteToHostException – This indicate that the client or server host is not connected to the network, or that there is no path from the client’s network to the server’s network due to some failure. Ø Java.net.ConnectException – The network of the remote server can be reached, but either no host has been assigned the specified address, or a host is reachable but no application is listening to the specified port on this protocol used. Additionally, the constructor may throw the runtime exception java.lang.SecurityException if a security manager has been installed, and the connect action has not been provided for the target IP address and port. A similar constructor is provided for use with host names, or IP addresses represented as Strings. The signature is as – 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. There is another equivalent constructor with the previous constructor, which is much more convenient – new Socket(InetAddress.getByName(host),port); Example of a simple program demonstrating Socket Creation – //SimpleClient.java import java.net.*; import java.io.*; import java.awt.*; import java.applet.*; import java.awt.event.*; public class SimpleClient { public static void main(String[] args) { String host = “sap_server”; Int port = 1234; try { System.out.ptintln(“Attemting to connect to a TCP service on host “ + host + “and port: “ + port); Socket s = new Socket(host,port); System.out.ptintln(“Connection Esteblished . . .“); } catch(UnknownHostException ue) { System.out.ptintln(“Trouble: “ + ue.getMessage()); Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[8]

} catch(IOException ioe) { System.out.ptintln(“Trouble: “ + ioe.getMessage()); } catch(SecurityException se) { System.out.ptintln(“Trouble: “ + se.getMessage()); } } } Reading - Writing Socket Connection oriented sockets are an abstraction for a byte-stream communication between two network programs. Therefore the most important methods of the Socket class are the ones that permit users to actually use instances for communication. 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 and java.io.OutputStream instances encapsulating the communication stream. 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. Getting Socket Information Connection oriented sockets encapsulate a connection to a network peer or remote host, therefore, they may be characterized by set: The four methods for querying the Socket local and remote addresses and port numbers are – InetAddress getInetAddress() throws IOException; int getPort() throws IOException; InetAddress getLocalAddress() throws IOException; int getLocalPort() throws IOException; Terminating socket As file objects also consume finite operating system resources. An open socket keeps a local port busy, and in most cases uses at least one native operating system file handle. Both port numbers as well as file handlers are limited and therefore it is very important to explicitly Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[9]

close sockets when the connection is no longer needed. The close(0 method requests asynchronous termination of the socket connection. The close() method will return immediately, even if data written before invocation has not completed transmission. The default semantics of the method invocation are that delivery of data written before invocation will continue to be attempted until successfully delivered. It is possible to limit the maximum duration of pending data delivery using the setSoLinger() method. void close() throws IOException; Once a socket has been closed the input and output stream may no longer be used. An attempt to read and write data from input stream and to output stream will result in IOException. An attempt to read and write data from input stream and to output stream will result in IOException. An alternative way to close a socket is to invoke a close(0 method on either the input or only the output directions of the connection. The two methods for effecting such behavior are – void shutdown Input() throws IOException; void shutdown Output() throws IOException; Example code illustrating reading/writing through Socket The example program implements a client, EchoClient, that connects to the EchoServer. The EchoServer simply receives data from client and echoes it back. EchoClient creates a socket thereby getting a connection to the Echoserver. It reads the input from the user on the standard input stream, and then forwards that to the EchoServer by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server. //EchoClient.java 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); in = new BufferedReader(new InputStreamReader (echoSocket.getInputStream()); }

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[10]

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)); 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(); } } EchoClient both writes to and reads from its socket, thereby sending data to and receiving data from the EchoServer. The three statements in the try block of the main method are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket. echoSocket = new Socket(“sap_server”,7); out = new PrintWrite(echoSocket.getOutputStream(),true); in = new BufferedReader(new InputStreamReader (echoSocket.getInputStream()); The first statement in this sequences creates a new Socket object and names it echoSocket. The Socket constructor used here requires the name of the machine and the port number to connect, the example program uses the host name “sap_server”. This is the name of a hypothetical machine on local network. The second argument is the port number. Port number 7 is the port on which the EchoServer listens. The second statement gets the socket’s output stream and opens a PrintWriter on it. Similarly, the third statement gets the socket’s input stream and opens a BufferedReader on it. The example uses readers and writers so that it can write Unicode characters over socket. To send data through the socket to the server, EchoClient simply needs to write to the PrintWriter. To get the server’s response, EchoClient reads from the BufferedReader. Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[11]

The next part of the program is the while loop. The loop reads a line at a time from the standard input stream and immediately sends it to the server by writing it to the PrintWriter connected to the socket. String userInput; While(!(userInput = stdIn.readLine()).equals(“quit”)) { out.println(userInput); System.out.println(“Echo: “ + in.readLine(0); } The last statement in the while loop reads a line of information from the BufferedReader connected to the socket. The readLine method waits until the server echoes the information back to the EchoClient. When readLine returns, EchoClient prints the information to the standard output. The while loop, continues until the user types an end-of-input character. That is, EchoClient reads input from the user, sends it to the EchoServer, gets a response from the server, and displays it, until it reaches the end-of-input. The while loop then terminates and the program continues, executing the nest four lines of code – out.close(); in.close(); stdIn.close(); echoSocket.close(); These lines of code fall into the category of housekeeping. A well behaved program shoul always cleans up after itself. These statements close the readers and writers connected to the socket and to the standard input stream, and close the socket connection to the server. The order here is important because any streams connected to the server should be close before the socket. 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. Creating ServerSocket The basic ServerSocket constructor takes a single argument, the TCP port number used in binding. If the constructor returns without throwing an exception then the server socket has successfully bound to the requested TCP port. 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. Therefore, if any process has created a socket bound to the specified port an IOException will be thrown.

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[12]

Some operating systems restrict certain port numbers ranges to “special” processes. Fro example, UNIX based operating systems do not allow user-privileged processes to bimd to ports lower than 1024. in addition to this, operating systems reserve some specific port numbers for certain standard services such as HTTP, FTP etc. The java.net.BindException will be thrown if the requested port is already in use. The IOException will be thrown if the operating system was unable to allocate resources for the request. A SecurityException will be thrown if a security manager has been installed and listen action has not been supplied for localhost. An additional constructor is also provided, which permits users to specify the size of the connection backlog queue. The ServerSocket generates a java.net.Socket object for an incoming connection in response to an accept() call. Server programs usually loop around the accept() call, spawning threads to process each connection. Because the client connection requests happen asynchronously, it is possible that new requests will be received before the server program has been able to invoke the accept() method. In such cases, the requests are placed in a queue, and retrieved on subsequent accept() invocations. If the rate of incoming connections exceeds its capacity to serve, the queue can grow infinitely. The clients queued will have to wait for a long time to receive service. The solution to this problem is to set an upper bound on the queue length. Once the queue fills, new connection requests will be rejected. The Java network library designers arbitrarily choose numbers 50 for the queue size. This constructor throws the same exceptions as the basic constructor, that is, IOException and SecurityException. The signature of this constructor is as follows – ServerSocket(int port,int backlog) throws IOException,SecurityException; The third and final constructor permits user to bind to a particular local interface. Port numbers are assigned per protocol per interface. The previous two constructors attempt to bind program to the specified port on all available interfaces. In some rare cases, it may be desirable to limit the exposure of the program on a mulithomed host. For example, consider a corporate server that is connected both to the Internet, as well as to the corporate network. If the service provided is to be restricted to the corporate interface. This can provide additional security, in addition to a security policy restricting accept action from internal hosts. The signature of this constructor is – Server Socket (int port, int backlog, Inet Address bind Address) throws IO Exception, Security Exception; Accepting Sockets 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. If no connection requests are pending then the method blocks until a request is made, or the optionally specified connection timeout has expired. The method may throw an IO Exception Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[13]

if the Server Socket has been closed, or a communications error is encountered. The method may also throw Security Exception if the incoming connection originated from a host/port not covered by an accept socket permission. //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()); } 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()); } } } Getting Server Socket Information 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 get InetAddress() method returns the IP address of the interface to which the server

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[14]

socket is bound. The simple server socket constructor binds the server socket to the requested port on all available interfaces. In such cases, the get InetAddress() method returns the special IP address 0.0.0.0 which should be interpreted as wild card (bound to all IP address). Obtaining the port the server socket is bound to involve a simple invocation of the get Local Port (). Inet Address get Inet Address (); int get Local Port (); Terminating Server Socket 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. If the accept () method is invoked on a closed socket then a java.net.Socket Exception will be thrown with a message indicating that the socket has been closed. The signature is as follows – void close () throws IO Exception; Example code illustrating the server side of the Echo Client The example program implements a server, Echo Server that accepts connection from the EchoClient, which was implemented by the program EchoClient.java. The EchoServer simply receives data from the client and echoes it back to Echo Client. The server program is implemented by class Echo Server which contains main method for the server program and perform the work of listening to the port establishing connections. //EchoServer.java 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)

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[15]

{ System.out.println(“Trouble : ” + ioe.getMessage()); } 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); //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()); } } } Echo Server listens to its client Echo Client. It receives data being Echo Client and send it back to the client as it is. The server program begins by creating a new Server Socket object to listen on a specific port. The port number used in this case is 4444. try { //Creating ServerSocket instance serverSocket = new ServerSocket(port); }

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[16]

catch(SecurityException se) { System.out.println(“Trouble : ” + se.getMessage()); } catch(IOException ioe) { System.out.println(“Trouble : ” + ioe.getMessage()); } Server Socket is a java.net.class that provides a system independent implementation of the server side of a client – server socket connection. The constructor of Server Socket throws an exception if it can’t listen on the specified port. (for example, the port is already being used. In this case, the Echo Server has to exit. If the server successfully connects to its port, then the Server Socket object is successfully created and the server continues to the next step – accepting a connection from a client. try { clientSocket = serverSocket.accept(); } catch(SecurityException se) { System.out.println(“Trouble : ” + se.getMessage()); } catch(IOException ioe) { System.out.println(“Trouble : ” + ioe.getMessage()); } The accept() method waits until a client starts up and requests a connection on the host and port of server. When a connection is requested and successfully established, the accept method returns a new socket object which is bound to a new port. The server can communicate with the client over this new socket and continue to listen for client connection requests on the Server Socket bound to the original, predetermined port. After the server successfully establishes a connection with a client, it communicates with the client using this code: Print Writer out = new Print Writer (client Socket.get out put stream() ); Buffer Reader in = new Buffered Reader (new Input stream Reader (Client Socket.get Input stream() ); The first statement here gets the client socket’s output stream and opens Print Writer on it. Similarly in the next statement gets the client Socket’s input stream and opens a Buffered Reader on it. String inputLine; boolean finished = true;

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

[17]

do { inputLine = in.ReadLine(); if(inputLine.equalsIgnoreCase(“quit”)) finished = true; out.println(“Received : “ + inputLine()); out.flush(); }while(!finished); To send data through the socket to the client Echo Server simply needs to write to the Print Writer. To get the client’s response, Echo Server reads from the Buffered reader. The next intensity part is do - while loop. The actual communication starts from this loop. The loop reads a line at a time from the Input stream and immediately sends it to the client by writing it to the Print Writer. The do - while loop continues until the client sends “quit” to it. The do – while loop terminates and the program continues to execute next lines of code: in.close (); out.close (); client.Socket.close (); server Socket.close (); first two statement close the readers and writers connected to the socket. Next two statements close the socket connections of client and server.

Compiled By: Sapna Saxena, Lecturer ,Chitkara University

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF