230306 TIL

이지섭·2023년 3월 5일
0

오늘의 공부

STOMP 요약정리

@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/stomp/chat") // 여기로 웹소켓 생성
			.setAllowedOrigins("http://*:8080", "http://*.*.*.*:8080")
			.setAllowedOriginPatterns("http://*:63342", "http://*.*.*.*:63342") // for intelliJ
			.withSockJS();
	}

	/*어플리케이션 내부에서 사용할 path를 지정할 수 있음*/
	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.setApplicationDestinationPrefixes("/pub");
		registry.enableSimpleBroker("/sub");
	}
	@MessageMapping(value = "/chat/message") // /pub/chat/message 에 메세지가 오면 동작
	public void message(ChatRequestDto message){
		ChatResponseDto savedMessage = chatService.saveMessage(message);
		template.convertAndSend("/sub/chat/group/" + savedMessage.getGroupId(), savedMessage);
	}
  • addEndpoint : 소켓 생성을 위한 경로
  • setAllowedOrigins : 소켓 통신을 위해 열려있어야 하는 경로
  • 클라이언트 입장
    • pub로 보낸다
      • pub로 보내는 메세지 안에 어디로 보낼지 도착지 정보도 들어있다.
      • 서로 다른 주소가 적힌 편지가 하나의 우체통에 모이듯
    • sub로 받는다
      • sub/chat/group/{groupId} 경로를 구독한다
  • 서버 입장
    • pub로 데이터가 들어온다
      • 저장 처리
    • sub로 데이터를 보낸다
      • 데이터 안에 들어있던 도착지 정보를 꺼내와서 해당 위치로 데이터를 뿌린다
      • 이 과정에서 사용되는 것이 Message Broker
      • 스프링의 기본 브로커인 SimpleBroker를 사용해도 되지만, 스프링의 메모리를 사용하므로 메세지가 많아질 경우 부담이 될 수 있다.

문제와 시도

socket info not found

GET http://localhost:63342/stomp/chat/info?t=1678038167739 404 (Not Found)
  • 웹소켓이 생성이 되지 않는 문제가 있었다.

해결과 학습

socket info not found

  1. StompWebSocketConfig에
    @EnableWebSocketMessageBroker 어노테이션 달려있는지 확인
  2. StompWebSocketConfig의 registerStompEndpoints에
    .withSockJS() 적용되어있는지 확인
  3. StompWebSocketConfig의 registerStompEndpoints에
    .setAllowedOrigins() 올바르게 허용되어있는지 확인
  • 위 3가지 과정을 거쳐가며 확인하였으나 문제가 발견되지 않았다.
  • 이후 프론트쪽 자바스크립트에서 소켓 생성 포트가 잘못 적용된것을 확인하고 수정하였다.
// var sockJs = new SockJS("http://localhost:63342/stomp/chat");
var sockJs = new SockJS("http://localhost:8080/stomp/chat");
  • 웹소켓은 생성시 HTTP 프로토콜로 HandShaking 하기 때문에 8080포트로 열어주어야 한다.
  • 그 과정에서 서버의 정보를 얻기 위해
    http://localhost:8080/stomp/chat/info 이하생략
    를 호출하게 된다.
  • 연결 시 info를 호출하는 이유?
    • WebSocket이 모든 브라우저에 적용되지 않기도 하고,
      프록시 서버가 도중에 연결을 끊어버리기도 하기 때문에
      이런 단점들을 보완한 WebSocketEmulation (SockJS)를 사용한다.
    • SockJS는 우선 WebSocket 연결을 시도하고,
      실패하였을 경우 Streaming, Long-Polling 등 다른 대체 기술로 연결을 시도한다.
    • 어떤 방법으로 연결해야 할 지 정보를 얻기 위해 info를 호출하는 것이다.
      • 서버가 WebSocket을 지원하는가?
      • Cookies를 지원하는가?
      • CORS Origin 정보
  • 웹소켓 기술에 관해 조금 더 알아봐야겠다. 재밌다...!

메모

  • 오류 발생 시 항상, 즉시 메모해두기
profile
Stop thinking. Just do it.

0개의 댓글

관련 채용 정보