LAB 14 - Serving Multiple Clients using java threads and sockets
Goal
- Implement a server, capable of accepting many connections at the same time
- The server object contains an HashMap. The keys of this hashmap are the first 100 Integers, while the values are the squares of the correspondent keys (key=5, value=25)
- Each client send a key(an object Integer between 1-100) and the server send back the value associated to this key.
- Be careful that the HashMap has to be synchronized, since different Sockets can access to it
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.