Simple Text Oriented Message Protocol (텍스트 기반의 메세지 프로토콜)

동작 과정

1. Stomp MessageBroker 설정

@Configuration
@EnableWebSocketMessageBroker
public class StompConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chatting") //handshake를 하기 위한 endpoint 지정
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic","/queue"); // /topic으로 시작되는 경로를 브로커의 타겟 경로로 설정
        registry.setApplicationDestinationPrefixes("/app"); // /app으로 시작되는 메시지는 @Messagemapping 어노테이션을 사용하여 처리
    }
}

2. endpoint 연결 / url 구독

stompClient.current.connect(
      {},
      function () {
        //subscribe(subscribe url,해당 url로 메시지를 받을때마다 실행할 함수)
				// /topic/채널번호(1) 을 구독
        stompClient.current.subscribe(`/topic/${channelId}`, function (e) {
          //e.body에 전송된 data가 들어있다
          showMessage(JSON.parse(e.body));
        });
      },
      function (e) {
        //에러 콜백
        alert("에러발생!!!!!!");
      }
    );

3. 메시지 전송

//메시지 브로커로 메시지 전송
function send(e) {
  e.preventDefault();

  const data = {
    channelId,
    sender: username,
    contents: message,
  };
  // send(destination,헤더,페이로드)
stompClient.current.send("/app/chat/send", {}, JSON.stringify(data));
  setMessage("");
}

4. @MessageMapping으로 받아와서 구독중인 클라이언트에게 메시지 전송

@MessageMapping("/chat/send")
@SendTo
public void sendMsg(@Payload Map<String, Object> data){

    //  /topic/채널번호 를 구독중인 클라이언트에게 메세지를 보낸다.
    simpMessagingTemplate.convertAndSend("/topic/" + data.get(" "), data);
}