Send message from a basic server to a specific client

心已入冬 提交于 2019-11-28 11:43:32

Yes, it is possible. You need to maintain a separate connection to each client. The ServerSocket class has an accept() function which returns a Socket object. That object represents a connection between two points, your server and one client. You can call ServerSocket.accept() multiple times in a loop to accept all incoming connections. Each Socket object returned will be for a different client.

In order to have the server send a message to a specific client, it will need to know which socket belongs to which client, so the clients will have to send some message to the server identifying themselves, and the server will need to read and interpret that message. Then it can respond with the appropriate response for that specific client.

Post your code if you are still having trouble.

UPDATE because you added code to the question: See the Android Documentation about creating threads. That will be a lot of reading beyond this post on stackoverflow.

As to accepting connections and starting threads, just do it in a loop:

for(int i = 0; i<5; i++){
    clientSocket = serverSocket.accept();
    // start a new thread, passing it the clientSocket as an argument
}

Other possibly useful links: https://developer.android.com/resources/articles/painless-threading.html https://developer.android.com/guide/topics/fundamentals/processes-and-threads.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!