如何通过Web套接字向连接的用户发送消息? [英] How to send a message through web socket to a connected user?
问题描述
我想通过Web套接字向特定用户发送消息.到目前为止,我可以打开Web套接字并像这样从客户端读取消息:
I want to send a message through a web socket to a specific user. So far I can open a web socket and read message from client like that:
@ServerEndpoint(value = "/wsep")
public class WebSocketEndpoint {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEndpoint.class);
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
try {
session.getBasicRemote().sendText("You are connected. Your ID is " + session.getId());
} catch (Exception e) {
LOGGER.error("Error on open web socket", e);
}
}
@OnMessage
public void onClientMessage(String message, Session session) {
LOGGER.info("Message from {} is: {}", session.getId(), message);
}
@OnClose
public void onClose(Session session) {
this.session = null;
LOGGER.info("{} disconnected", session.getId());
}
}
我有一个独立的服务,可以在目标用户中创建消息.我的Message
类是一个简单的POJO:
I have an independent service which creates message in destination to a user. My Message
class is a simple POJO:
public class Message {
private String fromUserName;
private String toUserName;
private String content;
...
}
在我的MessageService
中创建新消息时,我想通知接收者是否已连接.我想我必须添加方法WebSocketEndpoint.onServerMessage
:
When a new message is created in my MessageService
, I want to inform the receiver if he is connected. I think I have to add a method WebSocketEndpoint.onServerMessage
:
public void onServerMessage(Session session, Message message) {
session.getBasicRemote().sendText(message.getContent());
}
但是我不知道该怎么做.
But I don't know how to do something like that which works.
推荐答案
所有用户都将有一个ServerEndpoint实例.因此,它应该存储所有客户端会话.正如Vu.N所建议的那样,一种方法是使用地图:
There will be one instance of the ServerEndpoint for all your users. So, it should store all client sessions. As Vu.N suggested, one way you can do it is using a map:
Map<String, Session> sessions = new ConcurrentHashMap<>();
public void onOpen(Session session) {
String username = [...]
sessions.put(username, session);
}
然后,很容易将消息发送给用户:
Then, it will be easy to send the message to the user:
public void onServerMessage(Session session, Message message) {
sessions.get(message.getToUserName())
.getBasicRemote() // see also getAsyncRemote()
.sendText(message.getContent());
}
现在最难的部分是获取username
吗?
Now the hardest part is to get the username
?
在我过去的作品中,我通过3种方式来做到这一点:
In my past works, I've done it in 3 ways:
-
客户端连接到具有某些密钥"的URL.此密钥"将用于查找正确的用户名. WebSocket服务器端点将是这样的:
The client connects to a URL that has some "key". This "key" would be used to find the right username. The WebSocket server endpoint would be like this:
@ServerEndpoint(value="/wsep/{key}") // the URL will have an extra "key"
public class WebSocketEndpoint {
[...]
@OnOpen
public void onOpen(Session session, @PathParam("key") String key) {
String username = getUserNameWithKey(key);
sessions.add(username, session);
}
客户端在第一条消息中发送一些信息.您只需忽略@OnOpen部分:
The client sends some information in the first message. You just ignore the @OnOpen part:
@OnOpen
public void onOpen(Session session) {
LOGGER.info("Session open. ID: {}", session.getId());
}
@OnMessage
public void onMessage(Session session, String message) {
String username = getUserNameFromMessage(message);
sessions.add(username, session);
}
某些用户信息可以从Cookie,JWT或其他内容获得.您需要ServerEndpointConfig.Configurator
才能从请求中获取该信息.例如:
Some user info can be obtained from a cookie, JWT, or something. You'll need a ServerEndpointConfig.Configurator
to get that information from the request. For example:
public class CookieServerConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
Map<String,List<String>> headers = request.getHeaders();
sec.getUserProperties().put("cookie", headers.get("cookie"));
}
}
然后,服务器端点将指向该配置程序:
Then, the server endpoint will point to that configurator:
@ServerEndpoint(value = "/example2/", configurator = CookieServerConfigurator.class)
public class WebSocketEndpoint {
您将获得如下信息:
@OnOpen
public void onOpen(Session session, EndpointConfig endpointConfig) {
String username = getUsername((List<String>)endpointConfig.getUserProperties().get("cookie"));
您可以在此处看到一些有效的示例: https://github.com/matruskan/websocket-example
You can see some working examples here: https://github.com/matruskan/websocket-example
对于更复杂的系统,您也可以使用标记系统",而不是使用Map.然后,每个会话都可以接收发送到其任何标签的消息,并且发送到标签的消息可以定向到许多会话.
For more complex systems, you can also have a "tagging system", instead of using a Map. Then, each session can receive messages sent to any of its tags, and a message sent to a tag can be directed to many sessions.
这篇关于如何通过Web套接字向连接的用户发送消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!