Multi-threaded Client/Server in Java

What is a Thread?

All developers are familiar with writing sequential programs , each sequential programs has a beginning, an execution sequence, and an end. A thread is a single sequential flow of control within a program. It's an independent path of execution through program code. Most programs written today run as a single thread , causing problems when multiple events or actions need to occur at the same time. When multiple threads execute, one thread's path through the same code usually differs from the others. Every thread in Java is created and controlled by the java.lang.Thread Class.

There are two ways to create thread in java;

  1. Implement the Runnable interface (java.lang.Runnable)
  2. By Extending the Thread class (java.lang.Thread)

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously. A multi-threaded program contains two or more process that can run concurrently and each process can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. The process of executing multiple threads simultaneously is known as multithreading .

Multithreaded Socket Programming in Java

In the previous example we already saw how a Single Thread Socket Program is running. In that case there is only one client can communicate with the server. It will not allow simultaneous client connections. Try to start another client. You will see that the second client cannot be connected until the first client closes its connection. To allow simultaneous connections we should know multithreaded programming. Here in the following Multithreaded Socket Programming , you can connect more than one client connect to the server and communicate.

How it works?

For each client connection, the server starts a child thread to process the request independent of any other incoming requests.

Socket serverClient=server.accept(); ServerClientThread sct = new ServerClientThread(serverClient,counter);
The ServerClientThread is a new class extends Thread Class . Here you can see, rather than processing the incoming requests in the same thread that accepts the client connection, the connection is handed off to a client thread that processes the request. That way the thread listening for next incoming requests spends as much time as possible in the serverSocket.accept() call. That way the risk is minimized for clients being denied access to the server because the listening thread is not inside the accept() call. Here the client thread actually executes the request. In the meantime server can take multiple client requests and start the processing. So individual threads will be started and they will work in parallel . In this example the client send a number to the server and in response to each client, the server send back the square of the received number.

Multithreaded Server Socket program in Java

import*; import*; public class MultithreadedSocketServer { public static void main(String[] args) throws Exception { try{ ServerSocket server=new ServerSocket(8888); int counter=0; System.out.println("Server Started ...."); while(true){ counter++; Socket serverClient=server.accept(); //server accept the client connection request System.out.println(" >> " + "Client No:" + counter + " started!"); ServerClientThread sct = new ServerClientThread(serverClient,counter); //send the request to a separate thread sct.start(); } }catch(Exception e){ System.out.println(e); } } }

Server Client program

This Server Client thread class handled the request independent of any other incoming requests. The following Java program is the part of Multithreaded Server Socket program.

class ServerClientThread extends Thread { Socket serverClient; int clientNo; int squre; ServerClientThread(Socket inSocket,int counter){ serverClient = inSocket; clientNo=counter; } public void run(){ try{ DataInputStream inStream = new DataInputStream(serverClient.getInputStream()); DataOutputStream outStream = new DataOutputStream(serverClient.getOutputStream()); String clientMessage="", serverMessage=""; while(!clientMessage.equals("bye")){ clientMessage=inStream.readUTF(); System.out.println("From Client-" +clientNo+ ": Number is :"+clientMessage); squre = Integer.parseInt(clientMessage) * Integer.parseInt(clientMessage); serverMessage="From Server to Client-" + clientNo + " Square of " + clientMessage + " is " +squre; outStream.writeUTF(serverMessage); outStream.flush(); } inStream.close(); outStream.close(); serverClient.close(); }catch(Exception ex){ System.out.println(ex); }finally{ System.out.println("Client -" + clientNo + " exit!! "); } } }

Client Program

This is the real Client program that request connection to the server. For each Client, you need to open separate console window to run the client program.

import*; import*; public class TCPClient { public static void main(String[] args) throws Exception { try{ Socket socket=new Socket("",8888); DataInputStream inStream=new DataInputStream(socket.getInputStream()); DataOutputStream outStream=new DataOutputStream(socket.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(; String clientMessage="",serverMessage=""; while(!clientMessage.equals("bye")){ System.out.println("Enter number :"); clientMessage=br.readLine(); outStream.writeUTF(clientMessage); outStream.flush(); serverMessage=inStream.readUTF(); System.out.println(serverMessage); } outStream.close(); outStream.close(); socket.close(); }catch(Exception e){ System.out.println(e); } } }

How to run this program ?

When you finish coding and compiled the MultithreadedSocketServer, ServerClientThread and TCPClient program, first you have to start MultithreadedSocketServer Program from DOS prompt (console window) , then you will get a message " Server Started..." in your DOS screen, where the server program is running . Next step is to start Java TCPClient Socket Program in the same computer or other computers on the same network . When you start the client program , it will establish a connection to the Server and waiting input from client side. The client program repeatedly asks the user to input an integer, sends to the server, and receives the square of the integer from the server. If you want to test multiple client, for each Client, you need to open separate console window to run the client program. When the client send "bye" from client side the server closes the connection from client. From the following image, you can see how the Server and multiple clients communicate to the server.
Multi threaded socket programming in Java

If your Server and Client program running on same machine, then give "".

Socket socket=new Socket("",8888);

Otherwise give the IP Address of the machine that MultithreadedSocketServer is running on.