소수전공 5회차) socket.io를 활용한 채팅, room구현

2017. 12. 20. 22:48프로그래밍(주력)/JAVASCRIPT

app_room.js

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
const express = require("express");
const app = express();
const http = require('http').Server(app);
const fs = require('fs');
const io = require('socket.io')(http);
 
 
app.use(express.static(__dirname + '/public_room'));
app.get('*', (req, res) => {
    res.status(404).end();
});
 
let client_list = { room1: [], room2: [], room3: [] };
 
io.on('connection', (socket) => {
  socket.on('join', (data) => {
    socket.join(data.room);
      console.log(data);
    socket.room = data.room;
    socket.username = data.username;
    if (~Object.keys(client_list).indexOf(socket.room)) {
        console.log(socket.room);
        client_list[socket.room].push(socket.username);
        io.sockets.in(socket.room).emit('list', client_list[socket.room]);
    } else {
        socket.emit('join', {'msg''error'});
    }
  });
    socket.on('sendToSocket', (data) =>{
        console.log(data);
        let payload = {};
        payload.username = socket.username.replace(/</gi, "").replace(/>/gi, "");
        payload.message = data.replace(/</gi, "").replace(/>/gi, "");
        io.sockets.in(socket.room).emit('sendToClient', payload);
    });
    socket.on('disconnect', () => {
        console.log('a user disconnected');
        if (socket && socket.room) {
            let socket_idx = client_list[socket.room].indexOf(socket.username);
            client_list[socket.room].splice(socket_idx, 1);
            io.sockets.in(socket.room).emit('list', client_list[socket.room]);
         }
    });
});
 
http.listen(8081, () => {
    console.log('localhost:80 에서 실행중');
});
 
cs

./public_room/index.html

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
109
110
111
112
113
114
115
116
117
118
<!DOCTYPE html>
 
<html>
<head>
    <meta charset="utf-8">
    <title>소켓 채팅</title>
    <script src="/socket.io/socket.io.js"></script>
    <style>
        @font-face {
            font-family: "nanum-sqare";
            src:url("./font/NanumSquareOTFRegular.otf")format("opentype");
            font-style: normal;
            font-weight: normal;
        }
        body{
            font-family: nanum-sqare;
        }
        #msgshow {
            width: 500px;
            height: 500px;
            overflow: auto
        }
        #msgbox {
            width: 300px;
            height: 50px
        }
        #msgsend {
            border: none;
            width: 50px;
            height: 50px;
        }
        #usr {
            margin-bottom: 10px
        }
    </style>
    <script>
        const socket = io();
        let persontext = "";
        window.onload =
        ()=>{
          const usr_name_input = document.getElementById('username');
          const msg_send = document.getElementById('msgsend');
          const msg_inputbox = document.getElementById('msgbox');
          const msg_show = document.getElementById('msgshow');
          const user_list = document.getElementById('userlist');
          const login_btn = document.getElementById('login');
          const room_select = document.getElementById('room');
          const login_form = document.getElementById('login_form');
          const chat_form = document.getElementById('chat_form');
              chat_form.style.display = 'none';
          socket.on('list'function (data) {
                console.log(data);
                user_list.innerHTML = '' // clean
                for (var i = 0; i < data.length; i++) {
                    user_list.innerHTML += '<li>' + data[i] + '</li>';
                }
              });
          login_btn.addEventListener("click",()=>{
            const room = room_select.value;
            const username = usr_name_input.value;
            socket.emit('join', {'room' : room, 'username' : username});
            login_form.style.display = 'none';
                  chat_form.style.display = 'block';
          });
          socket.on('join'function () {
                chat_form.style.display = 'none';
            login_form.style.display = 'block';
 
              });
          msg_send.addEventListener("click",()=>{
            socket.emit('sendToSocket', msg_inputbox.value);
            msg_inputbox.value = "";
          });
          msg_inputbox.addEventListener("keypress",(e)=>{
            if(e.keyCode == 13){
              socket.emit('sendToSocket', msg_inputbox.value);
              msg_inputbox.value = "";
            }
          });
          socket.on('sendToClient', (data) =>{
              msg_show.innerHTML += '<p><span class="name">' + data.username + '</span> : <span class="msg">' + data.message +'</span></p>';
              msg_show.scrollTop = msg_show.scrollHeight;
          });
        };
 
 
    </script>
</head>
<body>
  <ul id="userlist">
  </ul>
  <div id = "login_form">
        <h1>로그인을 합시다</h1>
        <input type="text" id="username">
        <select id="room">
            <option value = "room1">Room 1</option>
            <option value = "room2">Room 2</option>
            <option value = "room3">Room 3</option>
        </select>
        <button id="login">로그인</button>
    </div>
 
    <div id='chat_form'>
      <div id="msgshow"></div>
      <div id="container">
          <div id="msg">
                  메세지:
                  <input type="text" autocomplete="off" id="msgbox">
                  <input type="button" value="보내기" id="msgsend"></button>
 
          </div>
 
      </div>
    </div>
</body>
</html>
 
cs


필자가 수업시간 이전에 짠 코드를 배운 것을 활용하여 바꾸어보았다.


첨부파일

soketchat.zip