LAB 14 - Serving Multiple Clients using java threads and sockets

Goal

Serving Multiple Clients

There is one problem with the simple server in lab 10. Suppose we want to allow multiple clients to connect to our server at same time. Typically, a server runs constantly on a server computer, and clients from all over the Internet may want to use the server at the same time. rejecting multiple connections allows any one client to monopolize the service by connecting to it for a long time. we can do better using threads.

Every time we know the program has established a new socket connection , that is, when the call to accept was successful, we will launch a new thread to take care of the connection between the server and that client. The main program will just go back and wait for the next connection.
For this to happen, the main loop of the server should look like this:

				 while(true)
				 {
				  Socket incoming = s.accept();
				  Runnable r = new ThreadedHandler(incoming);
				  
				  Thread t = new Thread(r);
				  t.start();
				 }
				 

The ThreadedHandler class implements Runnable and contains the communication loop with the client in its run method.

				 class ThreadedHandler implements Runnable
				 {
				 ...
				 public void run(){
				 try{
				 	 InputStream inStream = incoming.getInputStream();
					 OutputStream outStream = incoming.getOuputStream();
					 // process input and send response
					 incoming.close()
				 
				 
				 }
				 catch(IOException e){
				 
				 
				 }
				 }
				 }
				 

Because each connection starts a new thread, multiple clients can connect to the server at the same time.

Improving performance

In this code we spawn a separate thread for each connection. This approach is not satisfactory for high-performance servers. You can achieve greater performance using features of the java.nio package. See http://www-106.ibm.com/developerworks/java/library/j-javaio.