在 tomcat-8 示例中,我看到了一个使用 HTML5 网络套接字进行聊天的示例。
代码如下所示
public class ChatAnnotation {
private static final Log log = LogFactory.getLog(ChatAnnotation.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections =
new CopyOnWriteArraySet<>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
@OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
@OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, HTMLFilter.filter(message.toString()));
broadcast(filteredMessage);
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
log.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
此代码向所有连接到服务器的客户端发送一条消息。
但我只想向“Guest1”发送消息。
我认为 for 循环必须改变。
如何仅向“Guest1”发送消息。
最佳答案
将连接从集合转换为映射:
ConcurrentHashMap< String, ChatAnnotation> connections = new ConcurrentHashMap<>();
保留用户或您拥有的任何标识符,以将用户标识为 map 中的键。他们在广播方法中使用用户 key 从映射中获取连接对象,并仅向该用户发送消息,而不是遍历所有连接对象。
关于java - 在 tomcat websockets 中向单个客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22891603/