我有我的Android平板电脑,(服务器),我有我的三星S3(客户端1)和三星S4(客户端2)我让它们都连接(或者我没有创建一个新的线程,每个连接进来)到我的平板电脑(服务器),我把它们放在列表视图中,然后我创建了一个菜单,当我点击列表视图时,它会启动菜单并将命令发送到最后连接的设备(客户端2),即使我点击了在客户端1上。
如何将它与客户端1和客户端2彼此分开进行通信?我需要切换输出流吗? (甚至是一件事?)我是否需要使用ip和端口来回复? (再一次是那件事吗?)
我希望有人能够帮助我。
编辑;这不是一个listview问题,因为我不知道在套接字上需要做什么编码才能与彼此分开的客户端进行通信。
答案 0 :(得分:0)
此处的示例源自Writing the Server Side of a Socket(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.
*/