WebSockets with Spring Boot WebFlux: Real-Time Communication

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

WebSockets with Spring Boot WebFlux

📑 Table of Contents:

  1. What Are WebSockets?
  2. WebSockets vs SSE vs HTTP
  3. Why Use WebSockets in WebFlux?
  4. Adding WebSocket Support in Spring WebFlux
  5. Creating a WebSocket Handler
  6. Registering WebSocket Routes
  7. Building a WebSocket Client (JavaScript)
  8. Broadcasting Messages (Optional)
  9. Production Considerations
  10. 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

FeatureHTTPSSEWebSockets
ProtocolHTTP/1.1HTTP/1.1Custom over TCP
DirectionRequest/ResponseServer → ClientBi-directional
LatencyHighMediumVery low
Use CasesAPIs, FormsNotificationsChat, 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.