[英]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. 当消息进入时,确定与传入消息关联的userID /其他标识ID。 Then re-broadcast to all other sockets, but exclude the Socket associated with the ID that sent the message 然后重新广播到所有其他套接字,但排除与发送消息的ID关联的套接字
在服务器端创建一个包含所有客户端的列表...每次收到新的味精时,然后迭代该列表并使用套接字的端口作为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. 我所做的是,我有一个类ClientHandler
来处理每个单独客户端的连接。
Inside ClientHandler
I had a HashMap
. 在ClientHandler
内部,我有一个HashMap
。 I added each client that had connected to the HashMap
, with the Key
being the client id
. 我添加了每个已连接到HashMap
的client id
,其中Key
为client id
。 I used a UUID
rather than int
for the client id
. 我使用UUID
而不是int
作为client id
。
Inside this handler class, I had a sendMessage(String str)
method. 在此处理程序类中,我有一个sendMessage(String str)
方法。 Within this method, a for-each
loop that loops through each ClientHandler
object, checking the values
inside the HashMap
. 在此方法内,一个for-each
循环循环遍历每个ClientHandler
对象,并检查HashMap
的values
。 Inside this for-each
loop, I have an if
statement that checks whether you are writing to the ClientHandler
object with this
id. 在此for-each
循环中,我有一个if
语句,用于检查您是否正在使用this
ID写入ClientHandler
对象。 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. 如果检查返回false
,则继续将消息写在PrintWriter
,该消息将不会发送给编写消息的客户端。
This worked for me . 这对我有用 。 Might not work for you . 可能对您不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.