在tomcat-8示例中,我看到了使用HTML5 Web套接字进行聊天的示例。
代码如下所示
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<>();
在地图中保留用户或您需要用来标识用户的任何标识符。他们使用广播方法中的用户键从地图中获取连接对象,并且仅向该用户发送消息,而不是遍历所有连接对象。