본문 바로가기

Spring

[Spring Boot] 소켓 통신을 위한 Websocket 서버 구성

반응형

 

 

spring boot websocket 종속성 추가

 

implementation("org.springframework.boot:spring-boot-starter-websocket")

위가 같이 종속성을 추가하면 사용중인 spring boot의 버전과 호환되는 버전으로 설정된다.

 

websocket 환경설정

 

@Configuration
@EnableWebSocketMessageBroker
class WebsocketConfig(
    private val env: Environment
) : WebSocketMessageBrokerConfigurer {

    override fun configureMessageBroker(config: MessageBrokerRegistry) {
        config.enableSimpleBroker("/topic") //sub
        config.setApplicationDestinationPrefixes("/topic") //pub
    }

    /**
     * /websocket/~ 이후 주소로 엔트포인트 매핑
     * */
    override fun registerStompEndpoints(registry: StompEndpointRegistry) {
        registry.addEndpoint("/websocket/test").setAllowedOrigins("*")
    }
}

 

  • enableSimpleBroker() - "/topic" 접두사가 붙은 url을 구독하는 대상들에 한하여 브로커가 메세지를 전달한다.
  • setApplicationDestinationPrefixes() - "/topic" 접두사가 붙은 url로 발행한 메세지만 핸들러로 라우팅
  • addEndpoint() - websocket에 접근하기위한 Endpoint -> localhost:8000/websocket/test/topic 으로 발행 또는 구독시에만 메세지 발행, 구독이 가능하다.

 

websocket 메세지 발행 및 구독

@RestController
class ChattingController() {


    @MessageMapping("/chatting/pub/{chattingRoomId}")
    @SendTo("/topic/chatting/sub/{chattingRoomId}")
    fun sendNewMessage(
        @DestinationVariable chattingRoomId: String,
        @Payload message: String
    ): String {
		// 발행 전 동작 정의

        return message
    }
}

 

  • @MessageMapping() - 위의 prefix, endpoint 설정을 포함한 입력한 url로 발행된 메세지 구독
  • @SendTo() - 해당 메서드의 return값을 url을 구독하는 클라이언트에게 메세지 발행
  • @DestinationVariable - 구독 및 발행 url 의 pathparameter
  • @Payload - 수신된 메세지의 데이터
반응형