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:
org.springframework.boot
spring-boot-starter-webflux
👨💻 5. Creating a WebSocket Handler
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 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
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)
< 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:
Sinks.Many sink = Sinks.many().multicast().onBackpressureBuffer();
Flux 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.