如何仅从服务器向特定用户发送 websocket 消息?
我的 webapp 具有 spring 安全设置并使用 websocket。我在尝试仅将消息从服务器发送到 特定用户 时遇到了棘手的问题。
我阅读 手册 的理解是我们可以做的服务器
simpMessagingTemplate.convertAndSend("/user/{username}/reply", reply);
在客户端:
stompClient.subscribe('/user/reply', handler);
但我永远无法调用订阅回调。我尝试了许多不同的路径但没有运气。
如果我将它发送到 /topic/reply 它有效,但所有其他连接的用户也会收到它。
为了说明这个问题,我在 github 上创建了这个小项目: https ://github.com/gerrytan/wsproblem
重现步骤:
- 克隆并构建项目(确保你使用的是 jdk 1.7 和 maven 3.1)
$ git clone https://github.com/gerrytan/wsproblem.git
$ cd wsproblem
$ mvn jetty:run
导航至
http://localhost:8080
,使用 bob/test 或 jim/test 登录单击“请求用户特定消息”。预期:仅针对此用户在“仅收到给我的消息”旁边显示一条消息“hello {username}”,实际:未收到任何消息
原文由 gerrytan 发布,翻译遵循 CC BY-SA 4.0 许可协议
哦,
client side no need to known about current user
,服务器会为你做的。在服务器端,使用以下方式向用户发送消息:
注意:使用
queue
queue
sendToUser
topic
在客户端
解释
当任何 websocket 连接打开时,Spring 将为它分配一个
session id
(不是HttpSession
,分配每个连接)。当您的客户端订阅以/user/
开头的频道时,例如:/user/queue/reply
,您的服务器实例将订阅名为queue/reply-user[session id]
的队列当使用向用户发送消息时,例如:用户名是
admin
你将写simpMessagingTemplate.convertAndSendToUser("admin", "/queue/reply", message);
Spring 将确定哪个
session id
映射到用户admin
。 Eg: It found two sessionwsxedc123
andthnujm456
, Spring will translate it to 2 destinationqueue/reply-userwsxedc123
andqueue/reply-userthnujm456
, and it send your message有 2 个目的地到您的消息代理。消息代理接收消息并将其返回给您的服务器实例,该服务器实例持有与每个会话相对应的会话(WebSocket 会话可以由一个或多个服务器持有)。春季将将消息转换为
destination
session id
user/queue/reply
:wsxedc123
然后,它将消息发送到相应的Websocket session