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

前端 未结 2 1913
囚心锁ツ
囚心锁ツ 2021-01-03 10:50

I want to send message to user when he connects to spring websocket, I\'ve

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends          


        
2条回答
  •  情书的邮戳
    2021-01-03 11:45

    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 {
    
        @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/

提交回复
热议问题