SpringBootチャット(SockJS,Stomp)1を実施する.優先パラメータとデフォルト動作の実装


Dependency

  • Stomp
  • sockjs
  • spring-boot-starter-websocket
  • パッケージ構造



    Config.java

    package com.velog.config;
    
    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 Config implements WebSocketMessageBrokerConfigurer{
    
    	@Override
    	public void configureMessageBroker(MessageBrokerRegistry registry) {
    		//subscribe url
    		registry.enableSimpleBroker("/topic");
    		//publish url
    		registry.setApplicationDestinationPrefixes("/app");
    	}
    	@Override
    	public void registerStompEndpoints(StompEndpointRegistry registry) {
    		//SockJs 생성 url
    		
    		registry.addEndpoint("/chat").withSockJS();
    	}
    	
    
    	
    }

  • configureMessageBroker()
    subscribe、publish urlを設定します.

  • registerStompEndpoints()
    SockJSがエンドポイントを作成することを指定します.
  • chat.html

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <meta charset="UTF-8">
    	<title>Chating</title>
    	<style>
    		*{
    			margin:0;
    			padding:0;
    		}
    		.container{
    			width: 500px;
    			margin: 0 auto;
    			padding: 25px
    		}
    		.container h1{
    			text-align: left;
    			padding: 5px 5px 5px 15px;
    			color: #FFBB00;
    			border-left: 3px solid #FFBB00;
    			margin-bottom: 20px;
    		}
    		.chating{
    			background-color: #000;
    			width: 500px;
    			height: 500px;
    			overflow: auto;
    		}
    		.chating p{
    			color: #fff;
    			text-align: left;
    		}
    		input{
    			width: 330px;
    			height: 25px;
    		}
    	</style>
    </head>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script type="text/javascript">
    
    	var sender = 1;   //사용자
    	var chatRoom_id = 1;    // 채팅방 id
    	
    	//sockJs connect
    	function connect() {
        	//Config.java에서 지정한 endpoint로 SockJS 객체 생성
    	    var socket = new SockJS('/chat');
    	    stompClient = Stomp.over(socket);
    	    
    	    
    	    stompClient.connect({}, function () {
            	//subscribe(subcribe url,데이터 수신시 실행할 함수)
    	        stompClient.subscribe('/topic/'+chatRoom_id, function (e) {
    	            showMessage(JSON.parse(e.body));
    	        });
    	    });
    	}
    	
    	connect();
    	
    	//메시지를 보낼때 호출할 함수
    	function send() {
    	    data = {
    	    		'chatRoom_id': chatRoom_id, 
    	    		'sender' :sender,
    	    		'contents': $("#chatting").val(),
    	    		};
             // 파라미터 -> (destination, headers = {}, body = '')
    	    stompClient.send("/app/chat/send", {}, JSON.stringify(data));
            //input 값 비우기
    	    $("#chatting").val('');
    	}
    
    	// msg 화면에 표시
    	function showMessage(msg){
    			$("#chating").append("<p>" + msg.sender +" : "+ msg.contents + "</p>");
    	}
    </script>
    <body>
    	<div id="container" class="container">
    		<h1>채팅</h1>
    		<div id="chating" class="chating">
    		</div>
    		
    		<div id="yourMsg">
    			<table class="inputTable">
    				<tr>
    					<th>메시지</th>
    					<th><input id="chatting" placeholder="보내실 메시지를 입력하세요."></th>
    					<th><button onclick="send()" id="sendBtn">보내기</button></th>
    				</tr>
    			</table>
    		</div>
    	</div>
    </body>
    </html>
    チャットウィンドウの画面とスクリプトコード.

    SockJSController.java

    package com.velog.controller;
    
    import org.springframework.messaging.handler.annotation.MessageMapping;
    import org.springframework.messaging.simp.SimpMessagingTemplate;
    import org.springframework.stereotype.Controller;
    
    import com.velog.dto.MessageDTO;
    
    import lombok.RequiredArgsConstructor;
    
    @Controller
    @RequiredArgsConstructor
    public class SockJSController {
    	private final SimpMessagingTemplate simpMessagingTemplate;
        
        @MessageMapping("/chat/send")
        public void sendMsg(MessageDTO message) throws Exception {
            simpMessagingTemplate.convertAndSend("/topic/" + message.getChatRoom_id(),message);
        }
    }
    画面から送信されるJSONデータは、「パラメータ」(MessageDTO)で受信できます.
    convertAndSend()メソッドは、最初のパラメータの値(/topic/...)に使用されます.メッセージ・オブジェクトを所属するSockJSセッションに送信します.

    MessageDTO.java

    package com.velog.dto;
    
    import lombok.Getter;
    
    @Getter
    public class MessageDTO {
    	private Long chatRoom_id;
    	private String contents;
    	private Long sender;
    }
    
    スクリプトのsend()関数のデータ値にマッピングするクラス.データ型に注意

    実行結果



    開発者ツールを使用して、右ブラウザのsender値を2に設定し、続行します.

    Reference

  • https://myhappyman.tistory.com
  • https://salepark.tistory.com
  • https://stomp-js.github.io