2014-06-18 37 views
10

我試圖在春季使用websocket和使用sock.js實現推送通知。Websocket:如何將消息推送到目標用戶

這些代碼片段:

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個在線用戶,即:用戶1,用戶2,用戶3,用戶4和用戶5。我只想將通知發佈到user1和user2。你能告訴我如何實現這一目標嗎?我正在考慮在後端或前端做這件事。或者有另一種方法可以用春天來達到這個目的。

有人幫助我。

謝謝。

+0

http://stackoverflow.com/questions/23594671/spring-websocket-notification/23596605#23596605 –

回答

5

您可以使用SimpMessagingTemplate.convertAndSendToUser()調用來檢查User destinations以將消息定位到特定用戶。

請注意,要啓用此功能,您的用戶必須通過HTTP驗證。

+0

但這並沒有真正的幫助。當你使用'SimpMessageTemplate.convertAndSendToUser'時,如果你看看代碼,它實際上只是前綴'/ user/{username}',然後使用'SimpMessageTemplate.convertAndSend'方法。它實際上並沒有解決安全問題。 – Nitroware

+0

是的,它的確如此:這是一個特殊的隊列,用戶的唯一sessionId被附加到目的地並被代理透明地刪除。 嘗試一下,並驗證只有發起用戶能夠接收發送到那裏的消息:所有其他客戶端不是。 –

相關問題