JSP/SERVLET
2018.02.19 / 01:05

À¥ ¼ÒÄÏ - äÆÃ(Chatting) ÇÁ·Î±×·¥ ¸¸µé±â

µðÆÌ
Ãßõ ¼ö 234

À¥ ¼ÒÄÏ - äÆÃ(Catting) ÇÁ·Î±×·¥ ¸¸µé±â



1. Socket Contoller ¸¸µé±â

1
2
3
4
5
6
7
8
@Controller
public class SocketController {
     
    @RequestMapping("/chat")
    public String viewChattingPage() {
        return "chatting/chat";
    }
}


2. bean Ãß°¡

   - applicationContext¿¡ socketController Ãß°¡

1
<bean id="socketController" class="com.ktds.cocomo.handler.socket.web.SocketController" />


3. ws-config ¸¸µé±â

1
2
3
4
5
6
<bean id="echoHandler" class="com.ktds.cocomo.handler.EchoHandler" />
 
<websocket:handlers>
    <websocket:mapping handler="echoHandler" path="/echo-ws"/>
    <websocket:sockjs />
</websocket:handlers>



4. EchoHandler ¸¸µé±â

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package com.ktds.cocomo.handler;
 
import java.util.ArrayList;
import java.util.List;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
 
import com.ktds.cocomo.handler.socket.vo.MessageVO;
 
public class EchoHandler extends TextWebSocketHandler {
 
    private Logger logger = LoggerFactory.getLogger(EchoHandler.class);
 
    /**
     * ¼­¹ö¿¡ ¿¬°áÇÑ »ç¿ëÀÚµéÀ» ÀúÀåÇÏ´Â ¸®½ºÆ®
     */
    private List<WebSocketSession> connectedUsers;
 
    public EchoHandler() {
        connectedUsers = new ArrayList<WebSocketSession>();
    }
 
    /**
     * Á¢¼Ó°ú °ü·ÃµÈ Event Method
     *
     * @param WebSocketSession
     *            Á¢¼ÓÇÑ »ç¿ëÀÚ
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        connectedUsers.add(session);
 
        logger.info(session.getId() + "´ÔÀÌ Á¢¼ÓÇß½À´Ï´Ù.");
        logger.info("¿¬°á IP : " + session.getRemoteAddress().getHostName());
    }
 
    /**
     * µÎ °¡Áö À̺¥Æ®¸¦ ó¸®
     *
     * 1. Send : Ŭ¶óÀ̾ðÆ®°¡ ¼­¹ö¿¡°Ô ¸Þ½ÃÁö¸¦ º¸³¿
     * 2. Emit : ¼­¹ö¿¡ ¿¬°áµÇ¾î Àִ Ŭ¶óÀ̾ðÆ®¿¡°Ô ¸Þ½ÃÁö¸¦ º¸³¿
     *
     * @param WebSocketSession
     *            ¸Þ½ÃÁö¸¦ º¸³½ Ŭ¶óÀ̾ðÆ®
     * @param TextMessage
     *            ¸Þ½ÃÁöÀÇ ³»¿ë
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
 
        MessageVO messageVO = MessageVO.converMessage(message.getPayload());
        String hostName = "";
 
        for (WebSocketSession webSocketSession : connectedUsers) {
            if (messageVO.getType().equals("all")) {
                if (!session.getId().equals(webSocketSession.getId())) {
                    webSocketSession.sendMessage(
                            new TextMessage(session.getRemoteAddress().getHostName() + " ¢º " + messageVO.getMessage()));
                }
            } else {
                hostName = webSocketSession.getRemoteAddress().getHostName();
                if (messageVO.getTo().equals(hostName)) {
                    webSocketSession.sendMessage(
                            new TextMessage(
                                    "<span style='color:red; font-weight: bold;' >"
                                    + session.getRemoteAddress().getHostName() + "¢º " + messageVO.getMessage()
                                    + "</span>") );
                    break;
                }
            }
        }
 
        /*
         * Payload : »ç¿ëÀÚ°¡ º¸³½ ¸Þ½ÃÁö
         */
        logger.info(session.getId() + "´ÔÀÇ ¸Þ½ÃÁö : " + message.getPayload());
    }
 
    /**
     * Ŭ¶óÀ̾ðÆ®°¡ ¼­¹ö¿Í ¿¬°áÀ» ²÷¾úÀ»¶§ ½ÇÇàµÇ´Â ¸Þ¼Òµå
     *
     * @param WebSocketSession
     *            ¿¬°áÀ» ²÷Àº Ŭ¶óÀ̾ðÆ®
     * @param CloseStatus
     *            ¿¬°á »óÅÂ(È®ÀÎ ÇÊ¿äÇÔ)
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
 
        connectedUsers.remove(session);
 
        for (WebSocketSession webSocketSession : connectedUsers) {
            /*
             * ÀÚ½ÅÀÌ º¸³½ ¸Þ½ÃÁö¸¦ ¹ÞÁö ¾Ê´Â´Ù.
             */
            if (!session.getId().equals(webSocketSession.getId())) {
                webSocketSession.sendMessage(new TextMessage(session.getRemoteAddress().getHostName() + "ÅðÀåÇß½À´Ï´Ù."));
            }
        }
 
        logger.info(session.getId() + "´ÔÀÌ ÅðÀåÇß½À´Ï´Ù.");
    }
}


5. MessageVO ¸¸µé±â

1
2
3
4
5
6
7
8
9
10
11
private String message;
private String type;
private String to;
 
public static MessageVO converMessage(String source) {
    MessageVO message = new MessageVO();
    Gson gson = new Gson();
    message = gson.fromJson(source, MessageVO.class);
 
    return message;
}


6. chatting.jsp ¸¸µé±â

   - jquery, socketjs ½ºÅ©¸³Æ® Ãß°¡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>chat</title>
<script type="text/javascript" src="/board/js/jquery-1.12.1.js"></script>
<script type="text/javascript" src="/board/js/json2.js"></script>
<script type="text/javascript" src="/board/js/sockjs-1.0.3.min.js" ></script>
<script type="text/javascript" >
 
    var sock = null;
    var message = {};
 
    $(document).ready(function(){
         
        chatSock = new SockJS("/board/echo-ws");
         
        sock.onopen = function() {
             
            message={};
            message.message = "¹Ý°©½À´Ï´Ù.";
            message.type = "all";
            message.to = "all";
            chatSock.send(JSON.stringify(message));
        };
         
        chatSock.onmessage = function(evt) {
            $("#chatMessage").append(evt.data);
            $("#chatMessage").append("<br />");
            $("#chatMessage").scrollTop(99999999);
        };
         
        chatSock.onclose = function() {
            // sock.send("äÆÃÀ» Á¾·áÇÕ´Ï´Ù.");
        }
         
         $("#message").keydown(function (key) {
             if (key.keyCode == 13) {
                $("#sendMessage").click();
             }
          });
         
        $("#sendMessage").click(function() {
            if( $("#message").val() != "") {
                 
                message={};
                message.message = $("#message").val();
                message.type = "all";
                message.to = "all";
                 
                var to = $("#to").val();
                if ( to != "") {
                    message.type = "one";
                    message.to = to;
                }
                 
                chatSock.send(JSON.stringify(message));
                $("#chatMessage").append("³ª ->  " + $("#message").val() + "<br/>");
                $("#chatMessage").scrollTop(99999999);
                 
                $("#message").val("");
            }
        });
    });
</script>
</head>
<body>
    <input type="button" id="sendMessage" value="¿£ÅÍ" />
    <input type="text" id="message" placeholder="¸Þ½ÃÁö ³»¿ë"/>
    <input type="text" id="to" placeholder="±Ó¼Ó¸»´ë»ó"/>
    <div id="chatMessage" style="overFlow: auto; max-height: 500px;"></div>
</body>
</html>


8. SocketController¿¡ Ãß°¡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.ktds.cocomo.handler.socket.web;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class SocketController {
     
    @RequestMapping("/chat")
    public String viewChattingPage() {
        return "chatting/chat";
    }
     
    @RequestMapping("/paint")
    public String viewPaintingPage() {
        return "chatting/paint";
    }
}


12. °á°ú





Ãâó: http://cocomo.tistory.com/268 [Cocomo Coding]