IT/Spring

[spring boot] 스프링부트 채팅 프로그램 만들기 #2

jaewon_sss 2020. 9. 21. 18:41
반응형

Spring Boot 를 이용한

채팅 프로그램 만들기 # 2


지난번 채팅 프로그램 만들기 # 1 에 이어서...






저번 글에서 com.example.demo 만든 것 처럼


com.example.demo.config 와 com.example.demo.handler 패키지를 생성해주고


그 안에 class 파일을 생성해줍니다.




afterConnectionEstablished - 웹소켓 연결이 되면 동작하는 메소드

afterConnectionClosed - 웹소켓 연결이 종료되면 동작하는 메소드

handleTextMessage - 메시지를 발송하면 동작하는 메소드



상속받은 TextWebSocketHandler는 handleTextMessage를 실행시킵니다.





SocketHandler.java 코드




package com.example.demo.handler;
import java.util.HashMap;
 
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
 
@Component
public class SocketHandler extends TextWebSocketHandler {
    
    HashMap<String, WebSocketSession> sessionMap = new HashMap<>(); //웹소켓 세션을 담아둘 맵
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //소켓 연결시
        super.afterConnectionEstablished(session);
        sessionMap.put(session.getId(), session);
    }
    
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //소켓 종료시
        sessionMap.remove(session.getId());
        super.afterConnectionClosed(session, status);
    }
    
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        //메시지 발송시
        String msg = message.getPayload();
        for(String key : sessionMap.keySet()) {
            WebSocketSession wss = sessionMap.get(key);
            try {
                wss.sendMessage(new TextMessage(msg));
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}
cs









WebSocketConfig.java 코드





package com.example.demo.config;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
 
import com.example.demo.handler.SocketHandler;
 
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
 
    @Autowired
    SocketHandler socketHandler;
    
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(socketHandler, "/chating");
    }
}
cs



chat.jsp 코드


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<meta charset="UTF-8">
    <title>채팅</title>
    <style>
        .chating{
            background-color: #000;
            width: 500px;
            height: 500px;
            overflow: auto;
        }
        .chating p{
            color: #fff;
            text-align: left;
        }
        #yourMsg{
            display: none;
        }
    </style>
</head>
 
<script type="text/javascript">
    var ws;
 
    function wsOpen(){
        ws = new WebSocket("ws://" + location.host + "/chating");
        wsEvt();
    }
        
    function wsEvt() {
        ws.onopen = function(data){
            //소켓이 열리면 초기화 세팅하기
        }
        
        ws.onmessage = function(data) {
            var msg = data.data;
            if(msg != null && msg.trim() != ''){
                $("#chating").append("<p>" + msg + "</p>");
            }
        }
 
        document.addEventListener("keypress"function(e){
            if(e.keyCode == 13){ //enter press
                send();
            }
        });
    }
 
    function chatName(){
        var userName = $("#userName").val();
        if(userName == null || userName.trim() == ""){
            alert("사용자 이름을 입력해주세요.");
            $("#userName").focus();
        }else{
            wsOpen();
            $("#yourName").hide();
            $("#yourMsg").show();
        }
    }
 
    function send() {
        var uN = $("#userName").val();
        var msg = $("#chatting").val();
        ws.send(uN+" : "+msg);
        $('#chatting').val("");
    }
</script>
<body>
    <div id="container" class="container">
        <h1>채팅</h1>
        <div id="chating" class="chating">
        </div>
        
        <div id="yourName">
            <table>
                <tr>
                    <th>닉네임</th>
                    <th><input class="form-control form-control-sm" type="text" name="userName" id="userName"></th>
                    <th><button class="btn btn-sm btn-primary" onclick="chatName()" id="startBtn">등록</button></th>
                </tr>
            </table>
        </div>
        <div id="yourMsg">
            <table>
                <tr>
                    <th>메시지</th>
                    <th><input class="form-control form-control-sm" id="chatting" placeholder="보내실 메시지를 입력하세요."></th>
                    <th><button class="btn btn-sm btn-primary" onclick="send()" id="sendBtn">보내기</button></th>
                </tr>
            </table>
        </div>
    </div>
</body>
</html>
cs








브라우저를 여러개 띄워놓고 닉네임 설정한 뒤에 채팅을 입력하면 아래 영상처럼 나오는걸 확인할 수 있습니다.





반응형