简体   繁体   English

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

[英]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. 将有多个客户端在端口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();
          }

   }

}

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. 如果你可以隔离客户端处理方法,那么在新的类ClientHandler中也可以扩展Thread ,在run()你可以读取和写入流。 Then in your run() of NetworkModule : 然后在你的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. 通常,最好implement Runnable而不是extending Thread ,因为由于Java继承模型,您可以实现许多接口,但只能从单个类扩展。

That is not a good way for writing a server program! 这不是编写服务器程序的好方法!
you'd better have two classes : 你最好有两节课:

  • 1)client_handler : 1)client_handler:
    a class that handles the clients and is responsible of serving the clients. 一个处理客户端的类,负责为客户提供服务。 let's name it client_handler.java . 我们将它命名为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 . 客户端应该并行获取服务,因此,这个类应该扩展Thread或实现Runnable接口。

  • 2)Server : Another class that waits for clients to connect ! 2)服务器:等待客户端连接的另一个类! Let's name it : server.java 我们将它命名为:server.java
    this class will implement the main method ! 这个类将实现main方法!
    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 : 这是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). 您应该以这样的方式更改代码,以便从服务器端访问更多客户端以访问(处理)通过端口6069发送的数据。您的第二个客户端应用程序只是简单的一个,具有连接到活动服务器的实现逻辑(如果有的话,或基于某些规则等)。 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 . 我认为阅读有用: Knock Knock Protocol It will explain you a lot how things are managed and they work in your case. 它将向您解释如何管理事物并且它们适用于您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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