Spring中的@SendToUser仅在集成了Spring Security时才有效吗?

时间:2018-10-23 11:51:38

标签: spring spring-boot websocket spring-websocket

我从Springboot开始使用Websocket。因此,起初我已经成功创建了一个演示聊天应用程序,该应用程序将消息广播给每个用户。 现在,我不想向所有用户广播消息,而是想向一个特定用户发送消息,所以我偶然发现了@SendToUser注释。现在,我无法弄清楚此批注将如何工作。我的应用程序当前缺少包括Spring Security框架在内的任何注册过程。

任何人都可以给我指出一些有关该主题的好文章,也可以在不实现Spring Security的情况下使用此批注发送一对一的消息吗?

这是我到目前为止所做的:

//Controller
@Controller
public class MessageController
{

   @Autowired
   private SimpMessagingTemplate messagingTemplate;

   //This broadcasts to all users
   @MessageMapping("/send")
   @SendTo("/topic/greeting")
   public MessageBean send(MessageBean message)
   {
      message.setDate( ZonedDateTime.now() );
      return message;
   }

   //This is intended to particular user
   @MessageMapping("/message")
   @SendToUser("/topic/greeting")
   public MessageBean processMessage(@Payload MessageBean message)
   {
      message.setDate( ZonedDateTime.now() );
      return message;
   } 
}

// WebSocketConfig:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer
{

   /* (non-Javadoc)
    * @see org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer#configureMessageBroker(org.springframework.messaging.simp.config.MessageBrokerRegistry)
    */
   @Override
   public void configureMessageBroker( MessageBrokerRegistry config )
   {
      config.enableSimpleBroker( "/topic/", "/queue/" );
      config.setApplicationDestinationPrefixes( "/app" );
      config.setUserDestinationPrefix("/user"); 
   }

   /* (non-Javadoc)
    * @see org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer#registerStompEndpoints(org.springframework.web.socket.config.annotation.StompEndpointRegistry)
    */
   @Override
   public void registerStompEndpoints( StompEndpointRegistry registry )
   {
      StompWebSocketEndpointRegistration registration = registry.addEndpoint( "/secretum" );
      registration.setHandshakeHandler( new DefaultHandshakeHandler()
      {
         @SuppressWarnings("unused")
         public boolean beforeHandshake( ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map< String, String > attributes )
               throws Exception
         {
            if ( request instanceof ServletServerHttpRequest )
            {
               ServletServerHttpRequest servletRequest = ( ServletServerHttpRequest ) request;
               HttpSession session = servletRequest.getServletRequest().getSession();
               attributes.put( "sessionId", session.getId() );
            }
            return true;

         }

      } );
      registration.setAllowedOrigins( "*" ).withSockJS();
   }
}

//客户端:

var clentModule = angular.module('clentModule', []);

//Main Controller
clentModule.controller('clentController', function($scope) {
    var client;
    $scope.connectAndSubscribe = function()
    {
        var url = "ws://localhost:8080/secretum/websocket";
        client = webstomp.client(url);
        connected = function()
        {
            console.log("connected");
        }

        var headers = {};
        client.connect(headers,function(){
            console.log("successfuly connected");
            var subscription = client.subscribe("/topic/greetings",subscriptionCallback);
        });

        subscriptionCallback = function(data) {
            console.log("subscription data", data);
        }

        //var subscription = client.subscribe("/topic/greetings",subscriptionCallback);
        //console.log(subscription);
    };

    $scope.sendMessage = function()
    {
        //var subscription = client.subscribe("/topic/greetings",subscriptionCallback);
        $scope.message = {};
        $scope.message.sender = "xyz";
        $scope.message.reciever = "abc";
        var sendObject = JSON.stringify($scope.message);
        client.send("/topic/greetings", {priority: 9}, sendObject);
    };

});

我的问题来自客户端,由于服务器中没有存储用户信息,我应如何发送请求以将消息发送给特定用户。这就是我的第一个问题,这个注释在没有Spring安全性的情况下是否可以工作?

1 个答案:

答案 0 :(得分:0)

@Paras ...一旦您有了主意,请参阅此

使用@SendToUser并在订阅时在队列前面添加“ / user /”(仅限订户端)。休息有效的魔术:-)

代替

Java Server: @SendTo("/topic/showResult")

JS Client: stompClient.subscribe('/topic/showResult', function(calResult){  ....

使用:

Java Server: @SentToUser("/topic/showResult")

JS Client: stompClient.subscribe('/user/topic/showResult', function(calResult){ ....

贷方@RS ...

并覆盖

  WebSocketMessageBrokerConfigurer界面中的

configureClientInboundChannel()方法