HTTP 통신과 Web Socket 통신의 차이점
요청 ~ 응답 까지만 연결이 유지됨Stateful Protocol양방향 통신을 시도함양방향 통신이라고 부르는 이유는 HTTP 통신 처럼 클라이언트가 요청을 보내면 서버가 응답하는 방식을 사용하지만, Web Socket 은 클라이언트가 서버에 요청을 보내면, 서버가 구독 목록을 통해 클라이언트에게 요청을 보낼 수 있기 때문!양방향 통신을 기반으로 함publish ↔ subscribe 을 기반으로 동작함 (pub/sub)메시지 발행자 (메시지 보내는 유저) → 메시지 브로커 → 메시지 구독자 (메시지 받는 유저) 흐름으로 진행됨메시지 브로커를 사용해 구독자들에게 메시지를 브로드캐스팅하는 것RabbitMQ, KafkaCOMMAND
header1 : value1
header2 : value2
Body^@
Web Socket 을 사용한 실시간 채팅 흐름
채팅을 하고자하는 유저끼리 채팅방이 개설됨
만약 채팅방에서 메시지를 전송하고자 한다면 메시지 브로커에게 메시지를 보냄
메시지 브로커 URL, 메세지를 수신할 엔드포인트 (주제), 메시지 Bodyconst stompClient = new StompJs.Client({
brokerURL: 'ws://localhost:8080/gs-guide-websocket'
});
StompJs.Client 를 사용해 Web Socket 클라이언트를 생성하고, Spring STOMP 엔드포인트에 연결// 발신
function sendName() {
stompClient.publish({
destination: "/app/hello",
body: JSON.stringify({'name': $("#name").val()})
});
}
/app/hello 주제로 name의 내용을 담아 메시지를 발행@Controller
@RequiredArgsConstructor
public class GreetingController {
@MessageMapping("/hello") // 메시지를 수신할 엔드포인트 : /app/hello
@SendTo("/topic/greetings") // 메시지를 발신할 주제 : /topic/greetings
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
/app/hello/topic/greetings메시지를 전송했다면, 해당 주제를 구독하고 있는 유저들에게 메시지가 전송되고, 유저들이 메시지를 수신함
stompClient.onConnect = (frame) => {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', (greeting) => {
console.log("Send Message!!");
showGreeting(JSON.parse(greeting.body).content);
});
};
onConnect 콜백이 호출되는데, 이 때 연결상태를 true 로 변경함/topic/greetings 로 설정함
MessageHandler 를 2개로 나눈 이유는 두 핸들러의 목적이 다름SimAnnotationMethod : 발행된 메시지 Body 의 전처리가 필요한 경우StompBrokerRelay 에게 전달됨StompBrokerRelay : 전처리가 필요없고, 같은 주제를 구독한 유저들에게 전송만 하면 되는 경우Getting Started | Using WebSocket to build an interactive web application