Spring websocket send to specific people

前端 未结 2 1680
醉梦人生
醉梦人生 2020-12-23 18:02

I have added custom token based authentication for my spring-web app and extending the same for spring websocket as shown below

public class WebSocketConfig          


        
2条回答
  •  误落风尘
    2020-12-23 18:29

    In your Websocket controller you should do something like this :

    @Controller
    public class GreetingController {
    
        @Autowired
        private SimpMessagingTemplate messagingTemplate;
    
        @MessageMapping("/hello")
        public void greeting(Principal principal, HelloMessage message) throws  Exception {
            Greeting greeting = new Greeting();
            greeting.setContent("Hello!");
            messagingTemplate.convertAndSendToUser(message.getToUser(), "/queue/reply", greeting);
        }
    }
    

    On the client side, your user should subscribe to topic /user/queue/reply.

    You must also add some destination prefixes :

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            config.enableSimpleBroker("/topic", "/queue" ,"/user");
            config.setApplicationDestinationPrefixes("/app");
            config.setUserDestinationPrefix("/user");
        }
    /*...*/
    }
    

    When your server receive a message on the /app/hello queue, it should send a message to the user in your dto. User must be equal to the user's principal.

    I think the only problem in your code is that your "/user" is not in your destination prefixes. Your greetings messages are blocked because you sent them in a queue that begin with /user and this prefixe is not registered.

    You can check the sources at git repo : https://github.com/simvetanylen/test-spring-websocket

    Hope it works!

提交回复
热议问题