Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make multiple threads use the same socket to read and write?

**

There will be multiple clients sending messages to the server on port 6069.I am looking to handle multiple requests at the same time, but I am not sure the code below can do it.

There will be requests on socket's queue. Since there is only one thread it will execute its iteration on one request and then it will take next request from the queue. How can I serve multiple clients at the same time?

**

This is the class creating thread to listen on port 6069.

public class NetworkModule extends Thread {
  private ServerSocket serverSocket;

  public NetworkModule(int port) throws IOException {

    serverSocket = new ServerSocket(port);
  }

    public void run() {
      while (true) {

                /* Here I read strings from the inputstream and write
                  to outputstream corresponding to "serverSocket" and call
                functions from other classes*/
      }
    }

}


below is how Main class looks like

public class Main
{

   public static void main(String[] args) 
   {
       try
          {
            int port=6069;
             Thread t = new NetworkModule(port);
             t.start();

          }
       catch(IOException e)
          {
             e.printStackTrace();
          }

   }

}

like image 982
Prashant Singh Rathore Avatar asked Mar 17 '26 00:03

Prashant Singh Rathore


1 Answers

If you can isolate client handling method, say in a new class ClientHandler that also extends Thread where in run() you read and write to streams. Then in your run() of NetworkModule:

while (true) {
     Socket socket = serverSocket.accept(); // blocks until new client connects
     ClientHandler handler = new ClientHandler(socket); // pass reference to socket
     handler.start(); // start executing in new thread
}

Generally, it's better to implement Runnable instead of extending Thread, because you can implement many interfaces but extend only from a single class, due to Java inheritance model.

like image 115
AlmasB Avatar answered Mar 18 '26 12:03

AlmasB