简体   繁体   中英

Java sockets, server send message to multiple clients

I am one server and multiple clients via threads. The client(s) send their message to the server. I have worked out how to make the server send the message back to client like a echo system. If I have two clients, I want them to send their message to the server and the server should send it to the client that did not send the message ie the other client. How would I go about send the message back to all the clients apart from the one that send the message?

When the message comes in, determine what the userID / other identifying id the incoming message is associated with. Then re-broadcast to all other sockets, but exclude the Socket associated with the ID that sent the message

在服务器端创建一个包含所有客户端的列表...每次收到新的味精时,然后迭代该列表并使用套接字的端口作为id发送该味精...

I recently wrote a Chat program too. What I did was, I had a class ClientHandler that handles the connection for each individual client.

Inside ClientHandler I had a HashMap . I added each client that had connected to the HashMap , with the Key being the client id . I used a UUID rather than int for the client id .

Inside this handler class, I had a sendMessage(String str) method. Within this method, a for-each loop that loops through each ClientHandler object, checking the values inside the HashMap . Inside this for-each loop, I have an if statement that checks whether you are writing to the ClientHandler object with this id. If the check returns false , you go ahead and write the message on the PrintWriter and the message won't be sent to the client writing the message.

This worked for me . Might not work for you .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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