WebSocket with Sockjs & Spring 4 but without Stomp

Spring supports STOMP over WebSocket but the use of a subprotocol is not mandatory, you can deal with the raw websocket. When using a raw websocket, the message sent lacks of information to make Spring route it to a specific message handler method (we don’t have any messaging protocol), so instead of annotating your controller, you’ll have to implement a WebSocketHandler:

public class GreetingHandler extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        Thread.sleep(3000); // simulated delay
        TextMessage msg = new TextMessage("Hello, " + message.getPayload() + "!");
        session.sendMessage(msg);
    }
}

And then add your handler to the registry in the configuration (you can add more than one handler and use SockJS for fallback options):

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(greetingHandler(), "/greeting").withSockJS();
    }

    @Bean
    public WebSocketHandler greetingHandler() {
        return new GreetingHandler();
    }
}

The client side will be something like this:

var sock = new SockJS('http://localhost:8080/greeting');

sock.onmessage = function(e) {
    console.log('message', e.data);
}

Leave a Comment