0Pricing
WebSockets & Real-Time Systems with Spring · Lesson

WebFlux WebSocket Handlers

Implement reactive WebSocket handlers using Spring WebFlux for non-blocking I/O.

WebFlux WebSocket Handlers is a free WebSockets & Real-Time Systems with Spring lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the WebSockets & Real-Time Systems with Spring learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Reactive WebSockets with WebFlux

Welcome! In this lesson, we'll dive into implementing reactive WebSocket handlers using Spring WebFlux. This approach is key for building high-performance, non-blocking real-time applications.

Spring WebFlux leverages the power of Project Reactor (Flux and Mono) to handle WebSocket connections and messages asynchronously, making your applications highly scalable and efficient.

The WebSocketHandler Interface

At the core of WebFlux WebSockets is the WebSocketHandler interface. It's a functional interface, meaning it has a single abstract method that you'll implement.

This method, handle(WebSocketSession session), is invoked every time a new WebSocket connection is established. It returns a Mono<Void>, signaling when the handling of the session is complete.

import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

// Simplified interface definition
public interface WebSocketHandler {
  Mono<Void> handle(WebSocketSession session);
}

Implementing a Simple Echo Handler

Let's create a basic Echo Handler. This handler will receive incoming text messages from a client and immediately send them back. It's a fundamental example to demonstrate both receiving and sending reactive messages.

Notice the use of reactive operators like map and flatMap to process the message stream.

import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

public class EchoWebSocketHandler implements WebSocketHandler {

  @Override
  public Mono<Void> handle(WebSocketSession session) {
    // Receive messages, transform them into text messages,
    // then send them back to the client.
    return session.receive()
      .map(WebSocketSession::textMessage)
      .flatMap(session::send)
      .then(); // Signal completion once the receive stream ends
  }
}

Understanding WebSocketSession

The WebSocketSession object is crucial. It represents a single, active WebSocket connection with a client. Think of it as your direct line to that specific client.

Key methods of WebSocketSession:

  • receive(): Returns a Flux<WebSocketMessage> for incoming messages.
  • send(Publisher<WebSocketMessage>): Sends messages to the client.
  • getId(): Provides a unique identifier for the session.
  • textMessage(String payload): Helper to create a text message.

Receiving Messages Reactively

The session.receive() method is how your handler gets incoming messages. It returns a Flux<WebSocketMessage>, which is a stream of messages that arrive over time.

You can apply any of Project Reactor's powerful operators (like doOnNext, filter, map) to process these messages in a non-blocking way.

import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

public class LoggingHandler implements WebSocketHandler {

  @Override
  public Mono<Void> handle(WebSocketSession session) {
    return session.receive()
      .doOnNext(message -> {
        // Log the received message payload
        System.out.println("Received: " + message.getPayloadAsText());
      })
      .then(); // Ensures the Mono completes when the Flux finishes
  }
}

Sending Messages Reactively

To send data back to the client, you use session.send(Publisher<WebSocketMessage> messages). This method takes a Publisher (like a Flux or Mono) of messages you want to send.

You can create WebSocketMessage objects using session.textMessage(String payload) for text or session.binaryMessage(DataBuffer payload) for binary data.

import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;

public class TimeWebSocketHandler implements WebSocketHandler {

  @Override
  public Mono<Void> handle(WebSocketSession session) {
    // Create a Flux that emits a message every second
    Flux<WebSocketMessage> messagesToSend = Flux.interval(Duration.ofSeconds(1))
      .map(tick -> "Current time: " + System.currentTimeMillis())
      .map(session::textMessage); // Convert String to WebSocketMessage

    return session.send(messagesToSend);
  }
}

Configuring WebSocket Endpoints

After creating your WebSocketHandler, you need to register it so Spring WebFlux knows which URL path should map to which handler. This is typically done in a @Configuration class that implements WebSocketConfigurer.

The WebSocketHandlerRegistry allows you to map your handlers to specific paths and configure origins.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.WebSocketConfigurer;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerRegistry;

@Configuration
public class MyWebSocketConfig implements WebSocketConfigurer {

  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    // Map the EchoWebSocketHandler to the "/echo" path
    registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*");
  }

  @Bean
  public WebSocketHandler echoWebSocketHandler() {
    return new EchoWebSocketHandler(); // Your handler instance
  }
}

Full Server-Side Echo App

Here's a complete, runnable Spring Boot application that combines our WebSocketHandler and its configuration. This creates a functional WebSocket server ready to echo messages!

Run this application, and it will start listening for WebSocket connections on the /echo path.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import org.springframework.web.reactive.socket.server.WebSocketConfigurer;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerRegistry;
import reactor.core.publisher.Mono;

@SpringBootApplication
public class WebFluxEchoServerApplication {

  public static void main(String[] args) {
    SpringApplication.run(WebFluxEchoServerApplication.class, args);
  }

  @Configuration
  static class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
      registry.addHandler(echoWebSocketHandler(), "/echo").setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler echoWebSocketHandler() {
      // Inline implementation for simplicity in full example
      return new WebSocketHandler() {
        @Override
        public Mono<Void> handle(WebSocketSession session) {
          return session.receive()
            .map(WebSocketSession::textMessage)
            .flatMap(session::send)
            .then();
        }
      };
    }

    // Required for WebSocket handling in WebFlux
    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
      return new WebSocketHandlerAdapter();
    }
  }
}

Connecting with a JavaScript Client

To test your server, you can use a simple JavaScript client in a web browser's developer console. This code connects to your /echo endpoint, sends a message, and logs the response.

Make sure your Spring Boot application is running before attempting to connect!

const socket = new WebSocket('ws://localhost:8080/echo');

socket.onopen = (event) => {
  console.log('WebSocket connection opened:', event);
  socket.send('Hello from the client!');
};

socket.onmessage = (event) => {
  console.log('Received from server:', event.data);
};

socket.onclose = (event) => {
  console.log('WebSocket connection closed:', event);
};

socket.onerror = (error) => {
  console.error('WebSocket error:', error);
};

WebFlux Handler Check

You've learned about the core components of WebFlux WebSocket handlers. Let's test your understanding of the main method that initiates session handling.

Recap: WebFlux WebSocket Handlers

Fantastic work! You've successfully explored how to implement reactive WebSocket handlers using Spring WebFlux.

  • WebSocketHandler: The central interface for defining how to handle new connections.
  • WebSocketSession: Represents a single client connection, providing methods to receive() and send() messages.
  • Reactive Flow: Messages are handled using Project Reactor's Flux<WebSocketMessage> for incoming streams and Publisher<WebSocketMessage> for outgoing streams.
  • Configuration: You register your handlers to specific URL paths using a WebSocketConfigurer.

This reactive approach ensures your real-time applications are scalable, efficient, and robust!

Frequently asked questions

Is the “WebFlux WebSocket Handlers” lesson free?

Yes — the full text of “WebFlux WebSocket Handlers” is free to read here on the web, and the WebSockets & Real-Time Systems with Spring course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the WebSockets & Real-Time Systems with Spring course, upgrade to CoddyKit PRO.

What will I learn in “WebFlux WebSocket Handlers”?

Implement reactive WebSocket handlers using Spring WebFlux for non-blocking I/O. You practise WebSockets & Real-Time Systems with Spring with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start WebSockets & Real-Time Systems with Spring?

No prior experience is required. WebSockets & Real-Time Systems with Spring on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “WebFlux WebSocket Handlers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this WebSockets & Real-Time Systems with Spring lesson?

Yes. Every WebSockets & Real-Time Systems with Spring lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Introduction to Reactive Programming
  2. WebFlux WebSocket Handlers
  3. Building Reactive Real-Time Services
  4. Handling Backpressure in Reactive Streams
← Back to WebSockets & Real-Time Systems with Spring