0Pricing
WebSockets & Real-Time Systems with Spring · 강의

WebSocket 인터셉터

WebSocket 인터셉터를 활용하여 메시지와 연결 이벤트를 사전 처리하고 사후 처리합니다.

WebSocket 인터셉터은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Real-Time Systems with Spring 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Welcome to Interceptors!

In Spring WebSockets, Interceptors act like gatekeepers or event listeners that can observe and modify the WebSocket lifecycle.

They allow you to perform actions like logging, authentication, or modifying data at specific points during a connection or message exchange.

Lifecycle Hooks

Think of the WebSocket process:

  • Handshake: Initial HTTP request to upgrade to WebSocket.
  • Connection: WebSocket link is established.
  • Message Exchange: Data flows between client and server.
  • Disconnection: WebSocket link closes.

Interceptors let you "hook" into these stages.

Intercepting the Handshake

The HandshakeInterceptor is crucial for the very first step: the WebSocket handshake.

It lets you:

  • Inspect the HTTP request before the WebSocket connection is established.
  • Perform authentication or authorization checks.
  • Add attributes to the WebSocket session.

You can decide whether to allow the handshake to proceed.

Coding a Handshake Interceptor

Let's create a simple HandshakeInterceptor that logs when a connection attempt begins and ends. This is useful for monitoring or debugging.

Notice the beforeHandshake and afterHandshake methods.

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;

public class MyHandshakeInterceptor implements HandshakeInterceptor {

  @Override
  public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                 WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    System.out.println(">>> Handshake starting for: " + request.getURI());
    // 'attributes' map can be used to pass data to WebSocket session
    return true; // Allow handshake to proceed
  }

  @Override
  public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                             WebSocketHandler wsHandler, Exception exception) {
    System.out.println("<<< Handshake completed for: " + request.getURI());
    if (exception != null) {
      System.err.println("Handshake failed: " + exception.getMessage());
    }
  }
}

Integrating Handshake Interceptors

To make our MyHandshakeInterceptor active, we need to register it within our Spring Boot application's WebSocket configuration.

Run this code and try connecting to ws://localhost:8080/ws from a browser's developer console (e.g., new WebSocket('ws://localhost:8080/ws')) to see the logs!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;

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

// MyHandshakeInterceptor.java (nested for brevity)
class MyHandshakeInterceptor implements HandshakeInterceptor {
  @Override
  public boolean beforeHandshake(ServerHttpRequest req, ServerHttpResponse res,
                                 org.springframework.web.socket.WebSocketHandler h, Map<String, Object> a) {
    System.out.println(">>> Handshake: " + req.getURI());
    return true;
  }
  @Override
  public void afterHandshake(ServerHttpRequest req, ServerHttpResponse res,
                             org.springframework.web.socket.WebSocketHandler h, Exception e) {
    System.out.println("<<< Handshake done: " + req.getURI());
  }
}

// WebSocketConfig.java (nested for brevity)
@Configuration
@EnableWebSocket
class WebSocketConfig implements WebSocketConfigurer {
  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry r) {
    r.addHandler(new TextWebSocketHandler(), "/ws")
     .addInterceptors(new MyHandshakeInterceptor())
     .setAllowedOrigins("*");
  }
}

Intercepting STOMP Messages

While HandshakeInterceptor handles initial connections, ChannelInterceptor focuses on STOMP messages flowing through Spring's message broker.

These interceptors operate on the messaging channels, allowing you to inspect or modify messages before they reach their destination or after they are sent.

Coding a Channel Interceptor

A ChannelInterceptor provides methods like preSend, postSend, and afterSendCompletion.

The preSend method is commonly used to inspect or modify a message before it is sent to its destination (e.g., a STOMP topic or user queue).

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;

public class MyChannelInterceptor implements ChannelInterceptor {

  @Override
  public Message<?> preSend(Message<?> message, MessageChannel channel) {
    // Log the message or perform security checks
    System.out.println("Intercepted STOMP message: " + message.getHeaders());
    // You can modify the message here
    return message; // Return the message to proceed
  }

  // Other methods like postSend, afterSendCompletion...
}

Integrating Channel Interceptors

To register a ChannelInterceptor, you typically use a configuration class that extends WebSocketMessageBrokerConfigurer.

  • Use clientInboundChannel() to intercept messages coming from clients.
  • Use clientOutboundChannel() to intercept messages going to clients.

This allows fine-grained control over message flow.

Common Use Cases

Interceptors are powerful for many scenarios:

  • Authentication & Authorization: Validate users before connection or message delivery.
  • Logging: Track connection events and message traffic.
  • Session Management: Attach user-specific data to WebSocket sessions.
  • Message Modification: Add headers, filter content, or transform payloads.
  • Rate Limiting: Prevent abuse by limiting message frequency.

Interceptor Knowledge Check

You've learned about two main types of WebSocket interceptors in Spring. Let's see if you can distinguish their primary use cases.

Interceptors: Your WebSocket Control

Today, you learned about Spring's WebSocket Interceptors, powerful tools for controlling and observing your real-time communication.

  • Handshake Interceptors: For pre-connection logic.
  • Channel Interceptors: For STOMP message flow.

They are essential for building secure, robust, and observable WebSocket applications. Next, we'll explore message converter customization!

자주 묻는 질문

“WebSocket 인터셉터” 강의는 무료인가요?

네 — “WebSocket 인터셉터” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.

“WebSocket 인터셉터”에서 뭘 배우나요?

WebSocket 인터셉터를 활용하여 메시지와 연결 이벤트를 사전 처리하고 사후 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“WebSocket 인터셉터” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. WebSocket 인터셉터
  2. 메시지 변환기 사용자 지정
  3. 사용자 세션 관리
  4. 특정 사용자 대상 메시징
← WebSockets & Real-Time Systems with Spring(으)로 돌아가기