Search code examples
javaspringwebsocketspring-websocket

Launch spring WebSocket programmatically


After some time I got my WebSocket running with this config:

@Configuration
//@EnableWebSocket
public class WebSocketServerConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/var").setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new WebsocketServer();
    }
}

But I'm unable to find a way to launch this WebSocket from my code.

Is there a way to launch this WebSocket later in my program?

I found this document but it does not provide a way to implement a startWebSocket() function or something similar.


Solution

  • The document you linked shows an example, where it returns an instance of EchoWebSocketHandler.

    You could accept connections and implement your own logic for afterConnectionEstablished or handleMessage using some internal status to determine whether you should accept requests, i.e.

    @Configuration
     @EnableWebSocket
     public class MyConfiguration implements WebSocketConfigurer {
    
            @Override
            public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
                    registry.addHandler(echoWebSocketHandler(), "/echo").withSockJS();
            }
    
            @Bean
            public WebSocketHandler echoWebSocketHandler() {
                   //FooWebSocketHandler implements your specific logic
                    return new FooWebSocketHandler();
            }
     }
     public class FooWebSocketHandler extends AbstractWebSocketHandler {
       private boolean enabled;
       ...
        public void handleMessage(WebSocketSession session,
                          WebSocketMessage<?> message)
                   throws Exception {
         if (enabled) {//work
         } else {
           //disabled, i.e. throw exception or send data according to your api
         }
       }
     }