简体   繁体   中英

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();
          }

   }

}

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.

That is not a good way for writing a server program!
you'd better have two classes :

  • 1)client_handler :
    a class that handles the clients and is responsible of serving the clients. let's name it client_handler.java .
    One object of this class should be created for each client connected to the server.
    Clients should get services in parallel , hence , this class should extend Thread or implement Runnable interface .

  • 2)Server : Another class that waits for clients to connect ! Let's name it : server.java
    this class will implement the main method !
    server class should make a new thread on each connection , so that clients can get services in parallel .
    **********************************
    below , there is some code to demonstrate the things I told above :

     /*this is the server class i talked about : */ public class server{ static void main (String args[]){ ServerSocket ss = new ServerSocket (args[0]); while (true){ Socket s = ss.accept(); client_handler ch = new client_handler(s); Thread t = new Thread(ch); t.start(); } } } 

and here is a sample code for client_handler :

public class client_handler implements Runnable{
    private Socket s ;
    private Scanner in ;
    print PrintWriter out;

    public client_handler(Socket s){
        this.s =s;
        in= new Scanner(s.getInputStream());
        out= new PrintWriter(s.getOutputStream());        
    }

   public void run(){
      // this is the entry of your thread . 
      // you can analyse the request received here . and send responses !

   }
}

You should change your code in such way to provide access from server side for more clients to access (process) data sent through port 6069. Your client application which is second is just simple one with implemented logic to connect to active server (if any, or based on some rules, etc). Server application makes the magic to provide access. This means each client to see each message sent by other clients and vice-versa.

I think is useful to read: Knock Knock Protocol . It will explain you a lot how things are managed and they work in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM