웹소켓을 구현하면서 전체 흐름이 어떻게되는지 정리해보고자 한다
1. WebSocketConfig 만들기
1) 가장먼저 WebSocketConfig 를 만들어서 WebSocketMessageBrokerConfigurer를 상속 받는다
2) 내장 메서드인 registerStompEndpoints와 configureMessageBroker를 만든다
3) registerStompEndpoints : 클라이언트에서 웹소켓 연결할 때 사용할 API경로를 설정해주는 메서드
3-1) registerStompEndpoints 에서 SockJS와 연결 주소로 /chat 으로 설정해준다
이때 React에서 new SockJS("/chat") 로 받아서
새로운 핸드쉐이크 커넥션 (WebSocket 에 연결)을 생성할때 사용한다
쉽게 얘기해서 /chat이라는 연결주소로 소켓을 연결한다고 보면 된다
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat") // SockJS 연결 주소
.withSockJS();
}
3-2) UI에서 connect를 눌렀을때 app.js 파일에서 /chat을 받아서 소켓을 연결시킨다
이때 데이터가 들어오기 전까지는 대기 상태라고 보면 된다
$( "#connect" ).click(function() {
let socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
/**
* Connected: CONNECTED
* heart-beat:0,0
* version:1.1
*/
// 연결이 되면 여기에 멈춰있는 상태
stompClient.subscribe('/sub/chat/room/{roomId}', function (msg) {
console.log("===== subscribe ======")
let data = msg.body;
$("#greetings").append("<tr><td>" + data + "</td></tr>");
});
});
});
4) configureMessageBroker : 메시지 주고 받을 때 관련 경로를 설정하는 메서드
4-1) enableSimpleBroker 는 /sub가 붙은 url은 전부 messageBroker가 잡아서
해당 채팅방을 구독하고 있는 클라이언트에게 메시지를 전달한다고 설정하는것
4-2) setApplicationDestinationPrefixes 는 /pub이 붙은 url에 데이터를 보내는 설정
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/sub"); // localhost:8080/sub/chat/message
registry.setApplicationDestinationPrefixes("/pub"); // localhost:8080/pub/chat/message
}
4-3) 여기서 app.js 에 #send 함수를 보면
send("/pub/chat/message/1") 이런식으로 메시지브로커가 있는 MessageController로
JSON형태의 데이터를 보낸다 그러면 MessageController 에서 @MessageMapping 으로
보내온 메시지를 받고 로직을 수행한 다음 @SendTo로 /sub해서 app.js로 보내준다
app.js (send 부분)
$( "#send" ).click(function() {
stompClient.send("/pub/chat/message/1", {}, JSON.stringify({'name': $("#name").val()}));
});
MessageController
@MessageMapping("/chat/message/{roomId}") // /pub/chat/message/1 => 송신메시지
@SendTo("/sub/chat/room/{roomId}")
@ResponseBody
public ResponseDto<MsgContentResponseDto> requiredMessage(@AuthenticationPrincipal UserDetailsImpl userDetails,
MsgContentRequestDto msg,
@DestinationVariable String roomId) {
return ResponseDto.success(messageService.sendMessage(userDetails.getMember(), msg, roomId));
}
app.js (connect 안에 subscribe 부분)
stompClient.subscribe('/sub/chat/room/{roomId}', function (msg) {
console.log("===== subscribe ======")
let data = msg.body;
$("#greetings").append("<tr><td>" + data + "</td></tr>");
});
'Spring' 카테고리의 다른 글
[Spring] QueryDSL 메서드 및 활용 예시 모아보기(1) (0) | 2022.11.14 |
---|---|
[Spring] Spring Boot + QueryDSL 활용하기 (0) | 2022.11.14 |
[Spring] static과 templates (0) | 2022.10.31 |
[Spring] webSocket + Stomp 연습(2) (0) | 2022.10.30 |
[Spring] webSocket + Stomp 연습(1) (0) | 2022.10.29 |