⦁ Stomp를 사용한 채팅 기본 레퍼런스 코드 분석및 동작원리 이해
WebSocket 참고 : https://velog.io/@sago_mungcci/%EC%8B%A4%EC%A0%84-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-1415%EC%9D%BC%EC%B0%A8-%ED%9A%8C%EA%B3%A0
Spring과 함께 STOMP 메시징을 사용하여 채팅 기본 구조 이해해보자.
STOMP : Simple Text Oriented Messaging Protocol
Stomp는 메시징 전송을 효율적으로 하기 위해 나온 프로토콜이다.
기본적으로 pub/sub 구조로 되어있기때문에 메시지를 발송하고, 메시지를 받아 처리하는 부분이 명확하다.
개발과정에서 명확하게 인지하고 개발할 수 있다는 장점이있다.
또한 Stomp를 이용하면 통신 메시지의 헤더에 값을 세팅할 수 있어 헤더 값을 기반으로 통신 시 인증처리를 구현하는 것도 가능하다.
⦁ STOMP 프로토콜은 클라이언트/서버 간 전송할 메시지의 유형, 형식, 내용들을 정의한 규칙이다.
⦁ TCP 또는 WebSocket과 같은 [양방향 네트워크 프로토콜 기반]으로 동작한다.
⦁ 헤더에 값을 세팅할 수 있어서 헤더 값을 기반으로 통신 시 인증처리를 구현할 수 있다.
pub/sub란 메시지를 발송하고, 메시지를 받아 처리하는 부분을 구분하여 제공하는 메시징 방법이다.
예를들어 우체통(Topic)이 있다면 집배원(Publisher)은 우체통에서 편지를 꺼내 전달하고 , 우체통에서 집배원이 편지를 배달하는 것을 기다렸다가 배달이 오면 편지를 읽는 구독자(Subscriber)의 행위가 있다. 이때 구독자는 다수가 될 수 있다.
즉, 채팅방을 생성하는 것은 우체통 Topic을 만드는 것이고 채팅방에 들어가는 것은 구독자로서 Subsciber가 되는 것이다. 채팅방에 글을 써서 보내는 행위는 우체통에 편지를 넣는 Publisher가 된다.
implementation 'org.webjars:webjars-locator-core'
implementation 'org.webjars:sockjs-client:1.0.2'
implementation 'org.webjars:stomp-websocket:2.3.3'
implementation 'org.webjars:bootstrap:3.3.7'
implementation 'org.webjars:jquery:3.1.1-1'
MessageDto와 같은 역할을 하는 클래스이다.
이 클래스에 담긴 메시지가 소켓(Stomp)에 전달되서 실시간 채팅이 가능하다.
package com.example.messagingstompwebsocket;
public class HelloMessage {
private String name;
public HelloMessage() {
}
public HelloMessage(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
메시지를 담아서 전체적으로 반환해 주는 클래스이다.
package com.example.messagingstompwebsocket;
public class Greeting {
private String content;
public Greeting() {
}
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
굉장히 중요한 부분이다. 즉, 메시지가 해당 채팅방으로 실시간으로 전달하려면 이 WebSocketConfig에서 반드시 registerStompEndpoints를 사용해서 ws에 접근해야 된다.
채팅방의 생성 및 조회는 REST API로 구현한다. 그러나 메시지는 바로 WS(Stomp)를 이용해서 생성된 채팅방에 실시간으로 전달 할 수 있어야 한다.
package com.example.messagingstompwebsocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/*
* Stomp 사용을 위한 Message Broker 설정을 해주는 메소드이다.
*
1.enableSimpleBroker
* 메세지를 받을때, 경로를 설정해준다
* "/topic"이 api에 prefix로 붙은경우, messagebroker가 해당 경로를 가로챈다
*
2.setApplicationDestinationPrefixes
* - 메세지를 보낼때 관련 경로를 설정해주는 함수.
* - 클라이언트가 메세지를 보낼때,
api에 prefix로 "/app"이 붙어있으면 broker로 메세지가 보내진다.
*
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
}
package com.example.messagingstompwebsocket;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
package com.example.messagingstompwebsocket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MessagingStompWebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(MessagingStompWebsocketApplication.class, args);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/main.css" rel="stylesheet">
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
<script src="/app.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being
enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div id="main-content" class="container">
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="connect">WebSocket connection:</label>
<button id="connect" class="btn btn-default" type="submit">Connect</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="name">What is your name?</label>
<input type="text" id="name" class="form-control" placeholder="Your name here...">
</div>
<button id="send" class="btn btn-default" type="submit">Send</button>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetings</th>
</tr>
</thead>
<tbody id="greetings">
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
var stompClient = null;
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
참고 : https://spring.io/guides/gs/messaging-stomp-websocket/
참고 : https://ws-pace.tistory.com/106?category=968973
참고 : https://daddyprogrammer.org/post/4691/spring-websocket-chatting-server-stomp-server/
이거 기본예제 이해하는 것과 프런트와 연결해보고 같이 이해하는데에 하루가 다갔다.
아 그래도 채팅의 전반적인 흐름을 알게된것 같아서 너무 좋았다.