如何使用套接字处理连接到服务器的多个客户端?

Chu*_*cky 8 java sockets android client-server wifi-direct

我有一个Android应用程序,需要让多个设备连接.一个设备应该充当组所有者,并向所有客户发出指令以执行特定的操作.我认为它可以与一个玩家是主机的无线掌上游戏相媲美.

我有几个问题所以我会尽量保持简洁.即使对第一个问题的回答也会有所帮助.

首先,我使用套接字成功配对了单个服务器和单个客户端电话.我使用Android的Wi-Fi Direct技术(这里描述)做到了这一点.本教程很有帮助,但遗憾的是并不十分彻底,特别是在描述一对多连接时.找到对等列表后,可以打开套接字连接.我能够使用服务器的线程连接两个设备(使用此示例),如下所示:

public class ServerThread implements Runnable {

        public void run() {
             (Code...)
             client = serverSocket.accept();
             (...other code here.)
        }
}
Run Code Online (Sandbox Code Playgroud)

按下按钮后会创建一个客户端(我想,仍然试图了解我的修改后的代码):

public class MusicClientThread implements Runnable {
     Socket socket = new Socket(serverAddr, port);
     while (connected) {
          //(Other code here.)
          while ((line = in.readLine()) != null) {
          //While there are still messages coming
          }
     }
     socket.close();
     //(Other code here too.)
}
Run Code Online (Sandbox Code Playgroud)

所以我想我的第一个问题是:如何让更多客户连接?我的ServerThread指的是上面的单个客户端变量,所以我看不出如何允许变量(我的应用程序的目标是2到10个用户),我也不知道区分所有不同客户端的正确方法.我唯一的猜测是我会使用每部手机的唯一IP地址.

我的第二个问题是,一旦我与多个客户/同行建立了连接,我将如何正确地发送和接收指令?目前,我的单个服务器等待指令,并在收到指令后发出响应指令.我需要它,以便服务器可以使用按钮按钮从头开始发送指令,并且这些结果在客户端设备上可见.

我希望我已经把一切都搞清楚了!

ddm*_*mps 7

您必须为每个客户端启动一个新线程,因为套接字需要一个自己运行的线程(因为它在大多数时间等待输入).这可以例如完成(以这种简化的方式):

public class ThreadHandler extends Thread {
      private ArrayList<ServerThread> serverThreads = new ArrayList<ServerThread>();
      public void run() {
            while (!isInterrupted()) { //You should handle interrupts in some way, so that the thread won't keep on forever if you exit the app.
                  (Code...)
                  ServerThread thread = new ServerThread(serverSocket.accept());
                  serverThreads.add(thread);
                  thread.start();
            }
      }
      public void doSomethingOnAllThreads() {
            for (ServerThread serverThread : serverThreads) {
                  serverThread.otherMethod();
            }
      }
}
Run Code Online (Sandbox Code Playgroud)

ServerThread看起来像这样:

public class ServerThread extends Thread {
    private Socket socket;
    public ServerThread(Socket socket) {
          this.socket = socket;
    }
    public void run() {
         (...other code here.)
    }
    public void otherMethod() {
          //Signal to the thread that it needs to do something (which should then be handled in the run method)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 没必要道歉!在某些时候,每个人都是新手,我们随时为您提供帮助. (2认同)