WebFlux WebSocket 처리기
비차단 입출력을 위해 Spring WebFlux를 사용하여 반응형 WebSocket 처리기를 구현합니다.
WebFlux WebSocket 처리기은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Real-Time Systems with Spring 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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!
자주 묻는 질문
“WebFlux WebSocket 처리기” 강의는 무료인가요?
네 — “WebFlux WebSocket 처리기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.
“WebFlux WebSocket 처리기”에서 뭘 배우나요?
비차단 입출력을 위해 Spring WebFlux를 사용하여 반응형 WebSocket 처리기를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“WebFlux WebSocket 처리기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 반응형 프로그래밍 입문
- WebFlux WebSocket 처리기
- 반응형 실시간 서비스 구축
- 리액티브 스트림의 백프레셔 처리