多线程套接字输出流通信



我有我的安卓平板电脑(服务器(,我有三星S3(客户端1(和三星S4(客户端2(我让它们都连接(或者可能没有,我为每个连接创建了一个新线程(到我的平板电脑(服务器(,我把它们放在列表视图中,我创建了一个菜单,当我点击列表视图时,它会弹出菜单,它会向最后连接的设备(客户端2(发送命令,即使我点击了客户端1。

我如何才能将其与客户端1和客户端2分别进行通信?我需要切换输出流吗?(这是一件事吗?(我需要使用ip和端口进行响应吗?(再说一遍,这是一件事吗?(

我希望有人能帮我做这件事。

编辑;这不是列表视图问题,因为我不知道在套接字上进行什么编码才能与彼此独立的客户端进行通信。

这里的示例源于编写套接字的服务器端(oracle.com(。我强烈建议您尽快完成该示例代码。在您开始使用多个无线设备之前,在您的PC上本地执行此操作将非常容易。(我一直不明白为什么人们试图咬紧牙关,然后感到沮丧并放弃……在跑步之前学会走路!(

/**
  * Create a new server socket. This represents a TCP socket
  * in the LISTENING state, which means it is waiting for clients
  * to connect. It is not associated with any client.
  */
ServerSocket serverSocket = new ServerSocket(portNumber);
/**
 * Wait for a client to connect. This call will block (not return)
 * until a client successfully connects to the server.
 */
Socket clientSocket = serverSocket.accept();
/**
 * Whereas `serverSocket` represents the LISTENING socket, we
 * now have a `clientSocket`, which represents a single ESTABLISHED
 * connection with *a specific client*.
 */
/* Use this to receive data from the client... */
clientSocket.getInputStream();
/* ... or this to send data to the client. */
clientSocket.getOutputStream();
/**
 * At this point, the server is not yet ready for any new connections
 * from new clients. We can choose to either:
 *  o Handle this single connected clientSocket now, and deal with other
 *    clients when we're finished with this one. 
 *  o Spawn a new thread to handle this clientSocket
 *
 * Either way, we must go back to the top, and try to `accept`
 * another connection.
 */

最新更新