How to send message to user when he connects to spring websocket

狂风中的少年 提交于 2019-11-30 15:57:59

I would create SessionSubscribeEvent listener and use SimpMessagingTemplate inside.

Btw, configureClientInboundChannel is called only once (not for every user connected). So you have to handle sending message inside interceptor.

Try something like this:

@Service
public class SomeSubscribeListener {

    private SimpMessagingTemplate template;

    @Autowired
    public SomeSubscribeListener(SimpMessagingTemplate template) {
        this.template = template;
    }

    @EventListener
    public void handleSubscribeEvent(SessionSubscribeEvent event) {
        template.convertAndSendToUser(event.getUser().getName(), "/queue/notify", "GREETINGS");
    }
}

I hope this will help

you need a Websocketconfig file:

package mx.config.ws;
@EnableScheduling
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
   @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
       registry.addEndpoint("/chat").withSockJS()
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    ...
    }
}

And declare a nother @Configuration file:

package mx.config.ws;
@Configuration
public class WebSocketHandlersConfig {

    @Bean
    public StompConnectEvent webSocketConnectHandler() {
        return new StompConnectEvent();
    }

    @Bean
    public StompDisconnectEvent webSocketDisconnectHandler() {
        return new StompDisconnectEvent();
    }
}

Next create implementation of ApplicationListener interface. Automatically you will intercept the STOMP connections

package mx.config.ws;
public class StompConnectEvent implements ApplicationListener<SessionConnectEvent> {

    @Override
    public void onApplicationEvent(SessionConnectEvent event) {

         StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());

         System.out.println("StompConnectEvent::onApplicationEvent()    sha.getSessionId(): "+sha.getSessionId()+" sha.toNativeHeaderMap():"+sha.toNativeHeaderMap());


         //String  company = sha.getNativeHeader("company").get(0);
         //logger.debug("Connect event [sessionId: " + sha.getSessionId() +"; company: "+ company + " ]");



         // HERE YOU CAN MAYBE SEND A MESSAGE

    }

}

Check this link for a bout of information:
http://www.sergialmar.com/2014/03/detect-websocket-connects-and-disconnects-in-spring-4/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!