WebFlux-WebSocket-Handler
Implementieren Sie reaktive WebSocket-Handler mit Spring WebFlux für nicht blockierende E/A.
WebFlux-WebSocket-Handler ist eine kostenlose WebSockets & Real-Time Systems with Spring-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des WebSockets & Real-Time Systems with Spring-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der WebSockets & Real-Time Systems with Spring-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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 aFlux<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 toreceive()andsend()messages.- Reactive Flow: Messages are handled using Project Reactor's
Flux<WebSocketMessage>for incoming streams andPublisher<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!
Häufig gestellte Fragen
Ist die Lektion „WebFlux-WebSocket-Handler“ kostenlos?
Ja — der vollständige Text von „WebFlux-WebSocket-Handler“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des WebSockets & Real-Time Systems with Spring-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der WebSockets & Real-Time Systems with Spring-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „WebFlux-WebSocket-Handler“?
Implementieren Sie reaktive WebSocket-Handler mit Spring WebFlux für nicht blockierende E/A. Du übst WebSockets & Real-Time Systems with Spring mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um WebSockets & Real-Time Systems with Spring zu starten?
Keine Vorkenntnisse erforderlich. WebSockets & Real-Time Systems with Spring auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „WebFlux-WebSocket-Handler“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser WebSockets & Real-Time Systems with Spring-Lektion Code schreiben und ausführen?
Ja. Jede WebSockets & Real-Time Systems with Spring-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Einführung in die reaktive Programmierung
- WebFlux-WebSocket-Handler
- Reaktive Echtzeitdienste entwickeln
- Backpressure in reaktiven Streams verarbeiten