Spring 上的客户端和服务器映射消息如何启动 websocket

How client and server mapping message on Spring boot websocket

我在 github 上克隆了一个使用 spring 引导 websocket 的聊天应用程序项目。 这是代码:

@MessageMapping("/chat.private.{username}")
public void filterPrivateMessage(@Payload ChatMessage message, @DestinationVariable("username") String username, Principal principal) {

    message.setUsername(principal.getName());
    simpMessagingTemplate.convertAndSend("/user/" + username + "/exchange/amq.direct/chat.message", message);
}

例如:用户名变量为:foo@gmail.com,表示客户端的link订阅应该是:/user/foo@gmail.com/exchange/amq.direct/chat.message

但是在客户端代码中:

chatSocket = Stomp.over(new SockJS(url)); //use sockjs and stompjs
chatSocket.subscribe("/user/exchange/amq.direct/chat.message"

我不明白当客户端收听不同的 url(没有 foo@gmail.com)时,应用程序如何发送给正确的客户端。 有人可以给我解释一下吗?

谢谢。

关键是订阅url中的/user/前缀,会被Spring转化为特定用户投递消息。它在文档的 User Destinations 部分中进行了描述:

An application can send messages targeting a specific user, and Spring’s STOMP support recognizes destinations prefixed with /user/ for this purpose. For example, a client might subscribe to the destination /user/queue/position-updates. This destination will be handled by the UserDestinationMessageHandler and transformed into a destination unique to the user session, e.g. /queue/position-updates-user123. This provides the convenience of subscribing to a generically named destination while at the same time ensuring no collisions with other users subscribing to the same destination so that each user can receive unique stock position updates.