2017-07-25 46 views
1

我学习春天的WebSocket,我停留在如何我可以给使用@DestinationVariable("username") 这里消息发送到特定的用户是我的代码私人信息春天的WebSocket

configuration 
@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketContextConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> { 

    @Override 
    protected void configureStompEndpoints(StompEndpointRegistry registry) { 
     registry.addEndpoint("/ws-cfg").withSockJS(); 

    } 

    @Override 
    public void configureMessageBroker(MessageBrokerRegistry registry) { 
     registry.enableStompBrokerRelay("/queue/","/topic","/exchange/") 
       .setRelayHost("localhost"); 
     registry.setApplicationDestinationPrefixes("/app"); 
    } 
} 

控制器

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

     this.simpMessagingTemplate.convertAndSendToUser(username, "/queue/chat.message", message); 
    } 

客户端代码

var stomp = null; 
      stomp = Stomp.over(new SockJS("/ws-cfg")); 

      stomp.connect('guest', 'guest', function(frame) { 

       stomp.subscribe("/user/queue/chat.message", function (frame) { 
        dysplayMessage(JSON.parse(frame.body)); 
       }); 

      }) 


      $("#sendMessage").click(function (event) { 
       event.preventDefault(); 
       var message = $('#text').val(); 
       var username="[email protected]";// i am lost in this part, i supose this must be the @DestinationVariable("username") 
       destination = "/app/chat.private."+to; 
       stomp.send(destination, {}, JSON.stringify({'text': message})); 
       $('#text').val(""); 
      }); 

我目前使用websocket sp戒指安全。如何在stomp.send方法上设置@DestinationVariable("username")。 在此先感谢。

回答

0

退房已经是你正在寻找这个春天的WebSocket聊天样品:https://github.com/salmar/spring-websocket-chat

+0

首先,感谢你的我很高兴能和你说话!我正在研究该项目,并深入探索Spring WebSocket以及Spring WebSocket从零到英雄。我不知道如何将用户名从stomp.send方法传递给控制器​​方法。我认为从@DestinationVariable引用的用户名来自spring security,但事实并非如此。请任何消化? –