Search code examples
websocketsockjsspring-websocket

Websockets: Is it possible to add multiple Endpoints using SockJS?


I want to create 2 web socket endpoints. Can you tell is it possible?

What shall be the configuration in that case?


Solution

  • Your question does not clearly states if you're using plain websockets or STOMP messaging.

    Plain websocket API

    If you're using the plain websocket API, the registry API allows you to add as many websocket handlers as you want.

    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(myFirstHandler(), "/myHandler1").withSockJS();
            registry.addHandler(mySecondHandler(), "/myHandler2").withSockJS();
        }
    
        @Bean
        public WebSocketHandler myFirstHandler() {
            return new MyFirstHandler();
        }
    
        @Bean
        public WebSocketHandler mySecondHandler() {
            return new MySecondHandler();
        }
    
    }
    

    STOMP endpoints

    If you're using STOMP and would like to add several STOMP endpoints, then the API also allows you to do that (the addEndpoint method accepts a String vararg):

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/foo", "/bar").withSockJS();
    }