클라이언트
구독
stompClient.subscribe("/sub/room/123", callback)
/sub/room/123 이라는 주소에서 누군가가 메시지를 보내며느, 나에게도 그걸 알려달란뜻
채널을 트는 것과 비슷하며 수신대기 상태가 된다는 느낌
퍼블리시
stompClient.send("/pub/signal", {}, JSON.stringify(payload))
이건 클라이언트가 서버로 메시지를 보낸다는 뜻
그럼 서버는 이 메[시지를 받고, 상황에 따라 처리하거나 다른 클라이언트들에게 전달
브로커
메시지 흐름 정리
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
Spring에서 STOMP를 사용할 수 있도록 웹소켓 메시지 브로커 기능을 설정하는 클래스
WebSocketMessageBrokerConfigurer의 역할은 4개 정도 중요한 설정 메서드를 오버라이드 가능
configureMessageBroker()
→ 메시지 라우팅 규칙을 설정registerStompEndpoints()
→ 웹소켓 연결을 받을 Endpoint 설정configureClientInboundChannel()
→ 클라이언트에서 들어오는 메시지 채널 설정 (ex. 인터셉터 등)configureClientOutboundChannel()
→ 서버가 클라이언트로 내보낼 채널 설정package com.swu.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker // 웹소켓 + STOMP 활성화
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private final StompJwtInterceptor stompJwtInterceptor;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// 클라이언트가 구독할 수 있는 prefix
config.enableSimpleBroker("/sub");
// 클라이언트에서 메시지 보낼 때 prefix
config.setApplicationDestinationPrefixes("/pub");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOriginPatterns("*")
.withSockJS();
}
// WebSocket 연결 시 클라이언트의 STOMP 메시지를 가로채어 JWT 인증을 처리하기 위한 인터셉터 등록
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(stompJwtInterceptor);
}
}