In this post Learn how to build real-time, bi-directional communication channels using WebSockets in Spring Boot with WebFlux.

📑 Table of Contents:
- What Are WebSockets?
- WebSockets vs SSE vs HTTP
- Why Use WebSockets in WebFlux?
- Adding WebSocket Support in Spring WebFlux
- Creating a WebSocket Handler
- Registering WebSocket Routes
- Building a WebSocket Client (JavaScript)
- Broadcasting Messages (Optional)
- Production Considerations
- Final Thoughts
🔄 1. What Are WebSockets?
WebSockets provide a full-duplex communication channel over a single TCP connection. This allows the server and client to exchange messages at any time, without re-establishing a connection.
⚔️ 2. WebSockets vs SSE vs HTTP
Feature | HTTP | SSE | WebSockets |
---|---|---|---|
Protocol | HTTP/1.1 | HTTP/1.1 | Custom over TCP |
Direction | Request/Response | Server → Client | Bi-directional |
Latency | High | Medium | Very low |
Use Cases | APIs, Forms | Notifications | Chat, Games, Live Data |
⚡ 3. Why Use WebSockets in WebFlux?
Spring WebFlux handles WebSockets natively, providing a non-blocking and reactive pipeline using WebSocketHandler
and Reactor Flux
/Mono
.
Benefits:
- Non-blocking messaging
- Bi-directional streaming
- High scalability for real-time apps
🧱 4. Adding WebSocket Support in Spring WebFlux
WebFlux has built-in support, no extra dependencies needed if using:
1 2 3 4 5 6 7 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> |
👨💻 5. Creating a WebSocket Handler
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.kscodes.springboot.reactive.websocket; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.WebSocketSession; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component public class EchoWebSocketHandler implements WebSocketHandler { @Override public Mono<Void> handle(WebSocketSession session) { return session.send( session.receive() .map(msg -> "Echo: " + msg.getPayloadAsText()) .map(session::textMessage) ); } } |
💡 This handler reads incoming messages and sends back an echo response.
🧭 6. Registering WebSocket Routes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.kscodes.springboot.reactive.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import java.util.Map; @Configuration public class WebSocketConfig { @Bean public HandlerMapping handlerMapping(EchoWebSocketHandler handler) { return new SimpleUrlHandlerMapping(Map.of("/ws/echo", handler), 1); } } |
🌐 7. Building a WebSocket Client (JavaScript)
1 2 3 4 5 6 7 8 9 10 11 12 |
< script> const socket = new WebSocket("ws://localhost:8080/ws/echo"); socket.onopen = () => socket.send("Hello WebSocket!"); socket.onmessage = (event) => { console.log("Received:", event.data); }; < /script> |
✅ This connects to /ws/echo
and displays the echoed response.
📢 8. Broadcasting Messages (Optional)
For multi-client broadcast, use a shared FluxProcessor
:
1 2 3 4 5 6 7 |
Sinks.Many<String> sink = Sinks.many().multicast().onBackpressureBuffer(); Flux<String> messageStream = sink.asFlux(); sink.tryEmitNext("New message"); |
Use messageStream
in your WebSocketHandler
to push data to all clients.
🛠️ 9. Production Considerations
- Security: Use
wss://
over TLS in production - Scalability: Use Redis or Kafka to broadcast across clustered instances
- Timeouts: Configure proxy and server timeout settings for long-lived connections
- Monitoring: Keep track of active sessions and dropped connections
✅ 10. Final Thoughts
WebSockets in Spring Boot WebFlux make real-time, reactive applications easy to build and scale. With just a few lines of code, you can support chat apps, dashboards, game updates, and more.