Search code examples
javawebsocketserversocketjava-threads

JAVA multithreaded server sockets


Following is the code (JAVA) that accepts a client socket connection and assigns a thread to each connection.

 ServerSocket m_ServerSocket = new ServerSocket();

 while (true) {
            java.util.Date today = Calendar.getInstance().getTime();
            System.out.println(today+" - Listening to new connections...");

           Socket clientSocket = m_ServerSocket.accept();
           ClientServiceThread cliThread = new ClientServiceThread( clientSocket);
           cliThread.start();
 }

Suppose 5 clients are connected, hence 5 threads are running.

client 1: threadId 11
client 2: threadId 12
client 3 :threadId 13
client 4 :threadId 14
client 5 :threadId 15

Suppose one of the clients sends a message "kill-client1" , I to wish end client 1's connection and kill the thread with Id 11, something like this :

public void run() {
  try {
   BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
   PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

   while (running) {
    String clientCommand = in .readLine();

    if (clientCommand.equalsIgnoreCase("Kill-client1")) {
       // end the connection for client 1 & kill it's corresponding thread 11
    }
   }
 } catch (Exception e) {
  e.printStackTrace();
 }
 }

How can I achieve this ?


Solution

  • Just keep track of all client sockets and/or handling threads.

    Map<Integer,Socket> clients=new HashMap<>();
    
     while (true) {
                java.util.Date today = Calendar.getInstance().getTime();
                System.out.println(today+" - Listening to new connections...");
    
               Socket clientSocket = m_ServerSocket.accept();
               clients.put(generateNewClientId(),clientSocket);
               ClientServiceThread cliThread = new ClientServiceThread( clientSocket);
               cliThread.start();
     }
    

    And then if you simply do

    {
        if (clientCommand.equalsIgnoreCase("Kill")) {
           Socket socket=clients.get(idToShutDown);// get required id somehow (from request??)
           socket.close();
        }
    }
    

    This will close given socket resulting in breaking in.readLine() in handling thread thus finishing thread.

    If you keep track of threads, you can set "interrupt" flag and probe it in while condition so your handling thread will be able to finish work gracefully.