【发布时间】:2014-04-17 12:20:45
【问题描述】:
如何仅将 websocket 消息从服务器发送给特定用户?
我的 webapp 有 spring 安全设置并使用 websocket。我在尝试将消息从服务器发送到仅限特定用户时遇到了棘手的问题。
我阅读the manual的理解来自我们可以做的服务器
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}”,实际:未收到任何内容
【问题讨论】:
-
你一直在看 convertAndSendToUser(String user, String destination, T message) 吗? docs.spring.io/spring/docs/4.0.0.M3/javadoc-api/org/…
-
是的也试过了,但没有运气
-
我一直在从事私人项目,这是我们使用的方法,它对我们有用。我认为一个潜在的问题可能是您订阅了“/user/reply”并且您正在向“/user/{username}/reply”发送消息。我认为您应该删除 {username} 部分并使用 convertAndSendToUser(String user, String destination, T message)。
-
谢谢,但我试过
simpMessagingTemplate.convertAndSendToUser(principal.getName(), "/user/reply", reply);,当从服务器发送消息时,它会抛出这个异常java.lang.IllegalArgumentException: Expected destination pattern "/principal/{userId}/**" -
@ViktorK。是对的,你非常接近正确的解决方案。您在客户端的订阅是正确的,您只需尝试:
convertAndSendToUser(principal.getName(), "/reply", reply);
标签: java spring spring-mvc spring-websocket