Thursday 22 October 2009

Java Socket Programming

The Server
The server's main function is to wait for incoming requests, and to service them when they come in. So the code to implement the server can be further broken down to the following steps:
1. Establish a server that monitors a particular port. This is done by creating an instance of the ServerSocket class. There are four different ways to create an instance of ServerSocket. They are:
a. ServerSocket(), which simply sets the implementation that means everything is taken as default values. b. ServerSocket(int port), which creates a server-side socket and binds the socket to the given port number.c. ServerSocket(int port, int backlog), which not only binds the created socket to the port but also create a queue of length specified by the number passed as the backlog parameter. d. ServerSocket(int port, int backlog, InetAddress bindAddr), which creates a server-side socket that is bound to the specified port number with the queue of length specified by the backlog and bound to the address specified by the bindAddr argument.
So to create a socket bound to port number 8888 with a backlog queue of size 5 and bound with address of local host the statement would be:
ServerSocket server = new ServerSocket(8888, 5, InetAddress.getLocalHost() );
One point to keep in mind is that the above mentioned constructors return TCP sockets and not UDP sockets.
2. The next step is to tell the newly created server socket to listen indefinitely and accept incoming requests. This is done by using the accept() method of ServerSocket class. When a request comes, accept() returns a Socket object representing the connection. In code it would be:
Socket incoming = server.accept();
3. Communicating with the socket, which means reading from and writing to the Socket object. To communicate with a Socket object, two tasks have to be performed. First the Input and Output stream corresponding to the Socket object has to be obtained. That can be done by using the getInputStream() and getOutputStream() methods of Socket class. In code it would be:
BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream()));PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */);
The second task is to read from and write to the Socket object. Since the communication has to continue until the client breaks the connection, the reading from and writing to is done within a loop, like this:
boolean done = false; while (!done) { String line = in.readLine(); if (line == null) done = true; else { out.println("Echo: " + line);
if (line.trim().equals("BYE")) done = true; } }
The actual syntax for reading and writing is not different from the I/O done for simple files.
4. Once the client breaks the connection or stops sending the request, the Socket object representing the client has to be closed. This can be done by calling close() method on the Socket object. The statement would be:
incoming.close();
That's how a server is coded. The next section deals with creating a client.
The Client
The main purpose of the client is to connect to the server and communicate with it using the connection. So coding a client requires the following steps:
1. Connect to the server. Connecting to the server can be accomplished in two steps:
a. Creating a Socket object. The socket at client side just needs to know the host name (the name of the machine where server is running) and the port where the server is listening. To create a Socket object, there are seven constructors provided by the Socket class, of which the most commonly used are:
Socket(), which creates a new Socket instance without connecting to host.
Socket(InetAddress address, int port), which creates a new Socket object and connects to the port specified at the given address.
Socket(java.lang.String host, int port), which works the same way as Socket(), except that instead of an address, the host name is used.
So to create a Socket object that connects to 'localhost' at 8888, the statement would be:
Socket s=new Socket("localhost",8888);
b. Connecting to the server comes into picture if no argument constructor is used. It takes the object of the SocketAddress object as an argument. So to connect to localhost at port 8888, the code would be:
Socket s= new Socket();s.connect(new SocketAddress("localhost",8888));
2. Communicating with the server. Communicating with the server using a socket at client side is no different from how the server communicates with the client. First, the input and output streams connected with the Socket object are to be retrieved thus:
BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream()));PrintWriter out = new PrintWriter (s.getOutputStream(), true /* autoFlush */);
Then you read and write using the corresponding streams. For example, if the client just waits for the data sent by the server, the code would be
boolean more = true;while (more) { String line = in.readLine(); if (line == null) more = false; else System.out.println(line); }
That covers all the steps involved in creating a network enabled application. In the next section I will be developing a file server application with multi-threading to handle multiple clients.