如何让多个线程使用相同的socket来读写?

时间:2022-08-03 20:55:50

**

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.

将有多个客户端在端口6069上向服务器发送消息。我希望同时处理多个请求,但我不确定下面的代码是否可以执行此操作。

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.

这是创建要在端口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

下面是Main类的样子

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

   }

}

3 个解决方案

#1


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:

如果你可以隔离客户端处理方法,那么在一个新的类ClientHandler中也可以扩展Thread,在run()中你可以读取和写入流。然后在你的NetworkModule的run()中:

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.

通常,最好实现Runnable而不是扩展Thread,因为由于Java继承模型,您可以实现许多接口,但只能从单个类扩展。

#2


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 .

    1)client_handler:一个处理客户端的类,负责为客户端提供服务。我们将它命名为client_handler.java。应为连接到服务器的每个客户端创建此类的一个对象。客户端应该并行获取服务,因此,这个类应该扩展Thread或实现Runnable接口。

  • 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 :

    2)服务器:等待客户端连接的另一个类!我们命名一下:server.java这个类将实现main方法!服务器类应该在每个连接上创建一个新线程,以便客户端可以并行获取服务。 **********************************下面有一些代码来展示我上面讲的内容:

    /*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 :

这是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 !

   }
}

#3


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.

您应该以这样的方式更改代码,以便从服务器端访问更多客户端以访问(处理)通过端口6069发送的数据。您的第二个客户端应用程序只是简单的,具有连接到活动服务器的实现逻辑(如果有的话,或基于某些规则等)。服务器应用程序可以提供访问权限。这意味着每个客户端都可以查看其他客户端发送的每条消息,反之亦然。

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.

我认为阅读有用:Knock Knock Protocol。它将向您解释如何管理事物并且它们适用于您的情况。

#1


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:

如果你可以隔离客户端处理方法,那么在一个新的类ClientHandler中也可以扩展Thread,在run()中你可以读取和写入流。然后在你的NetworkModule的run()中:

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.

通常,最好实现Runnable而不是扩展Thread,因为由于Java继承模型,您可以实现许多接口,但只能从单个类扩展。

#2


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 .

    1)client_handler:一个处理客户端的类,负责为客户端提供服务。我们将它命名为client_handler.java。应为连接到服务器的每个客户端创建此类的一个对象。客户端应该并行获取服务,因此,这个类应该扩展Thread或实现Runnable接口。

  • 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 :

    2)服务器:等待客户端连接的另一个类!我们命名一下:server.java这个类将实现main方法!服务器类应该在每个连接上创建一个新线程,以便客户端可以并行获取服务。 **********************************下面有一些代码来展示我上面讲的内容:

    /*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 :

这是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 !

   }
}

#3


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.

您应该以这样的方式更改代码,以便从服务器端访问更多客户端以访问(处理)通过端口6069发送的数据。您的第二个客户端应用程序只是简单的,具有连接到活动服务器的实现逻辑(如果有的话,或基于某些规则等)。服务器应用程序可以提供访问权限。这意味着每个客户端都可以查看其他客户端发送的每条消息,反之亦然。

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.

我认为阅读有用:Knock Knock Protocol。它将向您解释如何管理事物并且它们适用于您的情况。