Backend Development 16 min read

WebSocket Integration in Spring Boot: Javax, WebMVC, and WebFlux Implementations

This article provides a comprehensive guide to implementing WebSocket in Spring Boot, covering server and client configurations for Javax, WebMVC, and WebFlux, along with code examples, deployment tips, and insights into alternative libraries such as Java-WebSocket, SocketIO, and Netty.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
WebSocket Integration in Spring Boot: Javax, WebMVC, and WebFlux Implementations

Introduction

The author shares a detailed study of various WebSocket integration methods in Spring Boot, focusing on three mainstream approaches—Javax, WebMVC, and WebFlux—while also giving a brief overview of other popular libraries.

Javax

Server

Define a WebSocket endpoint using @Component and @ServerEndpoint("/websocket/{type}") . Implement lifecycle callbacks with @OnOpen , @OnClose , @OnMessage , and @OnError to handle connections, messages, and errors.

@Component
@ServerEndpoint("/websocket/{type}")
public class JavaxWebSocketServerEndpoint {
    @OnOpen
    public void onOpen(Session session, EndpointConfig config, @PathParam("type") String type) {
        // connection established
    }
    @OnClose
    public void onClose(Session session, CloseReason reason) {
        // connection closed
    }
    @OnMessage
    public void onMessage(Session session, String message) {
        // receive text message
    }
    @OnMessage
    public void onMessage(Session session, PongMessage message) {
        // receive pong
    }
    @OnMessage
    public void onMessage(Session session, ByteBuffer message) {
        // receive binary
    }
    @OnError
    public void onError(Session session, Throwable e) {
        // error handling
    }
}

Register ServerEndpointExporter in a configuration class to enable the endpoint:

implementation 'org.springframework.boot:spring-boot-starter-websocket'
@Configuration(proxyBeanMethods = false)
public class JavaxWebSocketConfiguration {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

Client side uses @ClientEndpoint with the same lifecycle annotations.

@ClientEndpoint
public class JavaxWebSocketClientEndpoint {
    @OnOpen
    public void onOpen(Session session) { /* ... */ }
    @OnClose
    public void onClose(Session session, CloseReason reason) { /* ... */ }
    @OnMessage
    public void onMessage(Session session, String message) { /* ... */ }
    @OnError
    public void onError(Session session, Throwable e) { /* ... */ }
}

Connect using ContainerProvider.getWebSocketContainer() or, in a Spring environment, obtain the container via ServletContextAware implementation.

Message Sending

// send ping
session.getAsyncRemote().sendPing(ByteBuffer buffer);
// send pong
session.getAsyncRemote().sendPong(ByteBuffer buffer);

WebMVC

Server

Implement WebSocketHandler to process connection events and messages, then register the handler with @EnableWebSocket and a WebSocketConfigurer implementation.

public class ServletWebSocketServerHandler implements WebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) { /* ... */ }
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage
message) { /* ... */ }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) { /* ... */ }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { /* ... */ }
    @Override
    public boolean supportsPartialMessages() { return false; }
}
@Configuration
@EnableWebSocket
public class ServletWebSocketServerConfigurer implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new ServletWebSocketServerHandler(), "/websocket")
                .setAllowedOrigins("*");
    }
}

Handshake interceptors can be added by implementing HandshakeInterceptor . A custom UrlPathHelper can enable wildcard paths like /websocket/** .

Client

Use a similar WebSocketHandler implementation for the client and start the connection with WebSocketConnectionManager :

WebSocketClient client = new StandardWebSocketClient();
WebSocketHandler handler = new ServletWebSocketClientHandler();
WebSocketConnectionManager manager = new WebSocketConnectionManager(client, handler, uri);
manager.start();

WebFlux

Server

Reactive WebSocket handling uses org.springframework.web.reactive.socket.WebSocketHandler . The handler returns a Mono<Void> that combines sending and receiving streams.

public class ReactiveWebSocketServerHandler implements WebSocketHandler {
    @Override
    public Mono
handle(WebSocketSession session) {
        Mono
send = session.send(Flux.create(sink -> {
            // sink.next(message);
        })).doOnError(...);
        Mono
receive = session.receive()
            .doOnNext(...)
            .doOnError(...)
            .then();
        return Mono.zip(send, receive).then();
    }
}

Register the handler via a SimpleUrlHandlerMapping and enable it with a WebSocketHandlerAdapter bean.

@Component
public class ReactiveWebSocketServerHandlerMapping extends SimpleUrlHandlerMapping {
    public ReactiveWebSocketServerHandlerMapping() {
        Map
map = new HashMap<>();
        map.put("/websocket/**", new ReactiveWebSocketServerHandler());
        setUrlMap(map);
        setOrder(100);
    }
}

@Configuration(proxyBeanMethods = false)
public class ReactiveWebSocketConfiguration {
    @Bean
    public WebSocketHandlerAdapter webSocketHandlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}

Client

Instantiate a reactive client (e.g., ReactorNettyWebSocketClient ) and execute the handler:

WebSocketClient client = new ReactorNettyWebSocketClient();
WebSocketHandler handler = new ReactiveWebSocketClientHandler();
client.execute(uri, handler).subscribe();

Other Libraries

Java-WebSocket : a pure‑Java library for WebSocket, widely used on GitHub.

SocketIO : provides its own protocol and client/server APIs, suitable for real‑time chat scenarios.

Netty : a high‑performance networking framework that also supports WebSocket.

Conclusion

The article wraps up with a reminder to support the author and a brief promotion of a knowledge community.

Backend DevelopmentSpring BootWebSocketWebFluxJavaxwebmvc
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.