在 Spring Websocket 上向特定用户发送消息

新手上路,请多包涵

如何仅从服务器向特定用户发送 websocket 消息?

我的 webapp 具有 spring 安全设置并使用 websocket。我在尝试仅将消息从服务器发送到 特定用户 时遇到了棘手的问题。

我阅读 手册 的理解是我们可以做的服务器

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

  1. 导航至 http://localhost:8080 ,使用 bob/test 或 jim/test 登录

  2. 单击“请求用户特定消息”。预期:仅针对此用户在“仅收到给我的消息”旁边显示一条消息“hello {username}”,实际:未收到任何消息

原文由 gerrytan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 737
1 个回答

哦, client side no need to known about current user ,服务器会为你做的。

在服务器端,使用以下方式向用户发送消息:

 simpMessagingTemplate.convertAndSendToUser(username, "/queue/reply", message);

注意:使用 queue queue sendToUser topic

在客户端

stompClient.subscribe("/user/queue/reply", handler);

解释

当任何 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 session wsxedc123 and thnujm456 , Spring will translate it to 2 destination queue/reply-userwsxedc123 and queue/reply-userthnujm456 , and it send your message有 2 个目的地到您的消息代理。

消息代理接收消息并将其返回给您的服务器实例,该服务器实例持有与每个会话相对应的会话(WebSocket 会话可以由一个或多个服务器持有)。春季将将消息转换为 destination session id user/queue/replywsxedc123 然后,它将消息发送到相应的 Websocket session

原文由 Thanh Nguyen Van 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题