Websocket:如何将消息推送给目标用户

我正在尝试使用websocket并使用sock.js在spring中实现推送通知。

这些是代码片段:

public class NotifyController { @MessageMapping("/notifications") @SendTo("/get/notifications") public Greeting greeting(HelloMessage message) throws Exception { new Greeting("Hello, " + message.getName() + "!"); } } public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/get/notifications"); config.setApplicationDestinationPrefixes("/gssocket"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/notifications").withSockJS(); } } 

这是前面的代码..

  function connect() { var notificationSocket = new SockJS('/notifications'); stompNotificationClient = Stomp.over(notificationSocket); stompNotificationClient.connect({}, function(frame) { console.log('Connected: ' + frame); stompNotificationClient.subscribe('/get/notifications', function(greeting){ showGreeting(JSON.parse(greeting.body).content); }); }); } function sendNotification() { var name = "test" stompNotificationClient.send("/gssocket/notifications", {}, JSON.stringify({ 'name': name })); } 

我已经设法让它发挥作用。 但问题是,如何将消息推送给某些目标用户。 例如,有5个在线用户,即:user1,user2,user3,user4和user5。 我希望通知仅发布到user1和user2。 你能告诉我如何实现这个吗? 我想要在后端或前端进行。 或者还有另一种方法可以使用弹簧实现这一目标。

请有人帮帮我。

谢谢。

您可以使用SimpMessagingTemplate.convertAndSendToUser()调用来检查用户目标以使用您的消息定位特定用户。

请注意,要启用此function,您的用户必须经过HTTP身份validation。