Multithreaded server (Multiple Clients to a single server) programming in Java with Examples

In the last socket programming in Java post, I described how to build a single server and a single client connection using Java socket APIs. In this post, I explore the techniques needed to build a multi-clients, single server scheme in Java. We need to build a multithreaded server. This is a fundamental step in our work implementing Compute Server in Hadoop MapReduce.

I followed most of the tutorial here

Here are the steps I took to convert the EchoServer, EchoClient program showed here

to a multithreaded server.

The modifications only need to happen in the server side. The key here is that once server.accept() is invoked, all subsequent client requests will be blocked. That is if you run the original EchoServer, EchoClient program, the first client would work, but the second client would be blocked without a response.

In order to get around this, I have to create a thread for each socketServer.accept() call. This way, multiple client requests can be served simultaneously. To do this, we first implemented a ClientWorker class. It encapsulates the things we want to do after we established a connection. In this case, just send back to the client the original message the client.


The next step is using separate threads in EchoServer to invade the ClientWorker to handle incoming requests. The key components of the class is here



ClientWorker w;


//server.accept returns a client connection

w = new ClientWorker(serverSocket.accept());

Thread t = new Thread(w);


}catch(IOException e){

System.out.println("Accept failed: 4444");



The other parts of the class is here

The client code is left unchanged


This entry was posted in Java. Bookmark the permalink.

2 Responses to Multithreaded server (Multiple Clients to a single server) programming in Java with Examples

  1. p Manoj says:

    Thanks a lot … very good and very concise. Please keep guiding us more. thanks. sanjiv

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s