如何将 websocket 消息从服务器只发送给特定用户?
我的 webapp 有 spring 安全设置并使用 websocket。我在尝试将消息从服务器发送到仅限特定用户时遇到了棘手的问题。
我的阅读理解the manual来 self 们可以做的服务器
simpMessagingTemplate.convertAndSend("/user/{username}/reply", reply);
在客户端:
stompClient.subscribe('/user/reply', handler);
但我永远无法调用订阅回调。我尝试了许多不同的路径,但没有运气。
如果我将它发送到 /topic/reply,它会起作用,但所有其他连接的用户也会收到它。
为了说明问题,我在 github 上创建了这个小项目:https://github.com/gerrytan/wsproblem
重现步骤:
1) 克隆并构建项目(确保您使用的是 jdk 1.7 和 maven 3.1)
$ git clone https://github.com/gerrytan/wsproblem.git
$ cd wsproblem
$ mvn jetty:run
2) 导航到 http://localhost:8080
,使用 bob/test 或 jim/test 登录
3) 单击“请求用户特定消息”。预期:仅针对此用户的“仅接收给我的消息”旁边显示消息“hello {username}”,实际:未收到任何内容
最佳答案
哦,客户端不需要知道当前用户
,服务器会帮你做的。
在服务器端,使用以下方式向用户发送消息:
simpMessagingTemplate.convertAndSendToUser(username, "/queue/reply", message);
注意:使用 queue
,而不是 topic
,Spring 总是使用 queue
和 sendToUser
强>
在客户端
stompClient.subscribe("/user/queue/reply", handler);
解释
当任何 websocket 连接打开时,Spring 会为其分配一个 session id
(不是 HttpSession
,为每个连接分配)。当您的客户端订阅以 /user/
开头的 channel 时,例如:/user/queue/reply
,您的服务器实例将订阅名为 queue 的队列/reply-user[ session ID]
当使用发送消息给用户时,例如:用户名是admin
您将编写 simpMessagingTemplate.convertAndSendToUser("admin", "/queue/reply", message);
Spring 将确定哪个 session id
映射到用户 admin
。例如:它找到了两个 session wsxedc123
和 thnujm456
,Spring 会将其转换为 2 个目的地 queue/reply-userwsxedc123
和 queue/reply -userthnujm456
,它将带有 2 个目的地的消息发送到您的消息代理。
消息代理接收消息并将其提供回您的服务器实例,该实例持有与每个 session 对应的 session (WebSocket session 可以由一个或多个服务器持有)。 Spring会将消息翻译成destination
(例如:user/queue/reply
)和session id
(例如:wsxedc123
)。然后,它将消息发送到相应的Websocket session
关于java - 在 Spring Websocket 上向特定用户发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367223/