0Pricing
WebSockets & Real-Time Systems with Spring · Lección

Handlers WebSocket de WebFlux

Implemente handlers WebSocket reactivos mediante Spring WebFlux para operaciones de E/S no bloqueantes.

Handlers WebSocket de WebFlux es una lección gratuita de WebSockets & Real-Time Systems with Spring en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebSockets & Real-Time Systems with Spring, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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!

Preguntas frecuentes

¿La lección «Handlers WebSocket de WebFlux» es gratis?

Sí — el texto completo de «Handlers WebSocket de WebFlux» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebSockets & Real-Time Systems with Spring, actualiza a CoddyKit PRO. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

¿Qué aprenderé en «Handlers WebSocket de WebFlux»?

Implemente handlers WebSocket reactivos mediante Spring WebFlux para operaciones de E/S no bloqueantes. Practicas WebSockets & Real-Time Systems with Spring con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar WebSockets & Real-Time Systems with Spring?

No se requiere experiencia previa. WebSockets & Real-Time Systems with Spring en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Handlers WebSocket de WebFlux»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de WebSockets & Real-Time Systems with Spring?

Sí. Cada lección de WebSockets & Real-Time Systems with Spring incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción a la programación reactiva
  2. Handlers WebSocket de WebFlux
  3. Construcción de servicios reactivos en tiempo real
  4. Gestión del backpressure en streams reactivos
← Volver a WebSockets & Real-Time Systems with Spring