Node.js

웹소켓(WebSocket) 3장 - ws 라이브러리를 이용한 다중 클라이언트 채팅방

blackbearwow 2023. 6. 4. 00:51

- 어떻게 클라이언트들을 구분하는가? 

처음에는 wsList를 만들어서 클라이언트들을 구분하려 했다. 

const wss = new webSocket.Server({
    port: 8081
})
let wsList = [];
wss.on('connection', (ws, req) => {
    ws.on('error', console.error);
    console.log(req.socket.remoteAddress);
    wsList.push(ws);
    ws.on('message', (msg) => {
        console.log(`from client: ${msg}`);
    })
    ws.on('close', ()=>{
        console.log(`한명이 떠났다.`);
        wsList = wsList.filter((value)=>value != ws)
    })
})
rl.on("line", function(line){
    wsList.forEach((ws)=>{
        ws.send(line);
    })
    console.log(`연결된 클라이언트 수: ${wsList.length}`);
})

하지만, 구글링을 해보니 wss에서 clients라는 변수를 사용할 수 있다고 한다.

해당 내용: https://stackoverflow.com/questions/13364243/websocketserver-node-js-how-to-differentiate-clients

클라이언트가 접속, 종료 할 때마다 어떤 클라이언트가 있는지 관리할 필요가 없다. wss.clients가 자동으로 관리해준다.

 

const express = require('express');
const app = express();
const webSocket = require('ws');
const port = 8888;

const rl = require("readline").createInterface({ 
    input: process.stdin, output: process.stdout 
});

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.listen(port, function () {
    console.log(`listening on ${port}`);
});

app.get('/', function (req, res) {
    const title = "이게 타이틀 입니다.";
    res.render('client', { title, count: 5 });
})

const wss = new webSocket.Server({
    port: 8081
})

wss.broadcast = (message) => {
    wss.clients.forEach((val)=>{
        val.send(message);
    })
}

wss.on('connection', (ws, req) => {
    wss.broadcast(`새로운 접속. 현재 인원: ${wss.clients.size}`);
    ws.on('error', console.error);
    console.log(req.socket.remoteAddress);
    ws.on('close', ()=>{
        wss.broadcast(`한명이 떠났다. 현재 남은 인원: ${wss.clients.size}`);
    });
    ws.on('message', (msg) => {
        console.log(`from client: ${msg}`);
        wss.broadcast(msg.toString());
    });
})

rl.on("line", function(line){
    wss.broadcast(`서버: ${line}`);
})

-server.js-

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <%= title %>
    </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script>
        let socket = new WebSocket("ws://127.0.0.1:8081");
        socket.addEventListener('message', function(){
            let temp = `<div>${event.data}</div>`
            $('#chatLog').append(temp);
        })
        let btn;
        $(document).ready(function () {
            btn = $('#btn');
            btn.on('click', function () {
                let nickname = $('#nickname').val();
                let clientText = $('#clientText').val()
                socket.send(`${nickname}: ${clientText}`);
            })
        })
    </script>
</head>

<body>
    <div>
        <input id="nickname" type="text" placeholder="닉네임">
        <input id="clientText" type="text" placeholder="채팅">
        <button id="btn">전송하기</button>
    </div>
    <div id="chatLog">
        <div><center><b>채팅로그</b></center></div>
    </div>
</body>

</html>

-client.ejs-

wss에 boradcast라는 메소드를 만들어 접속한 모든 클라이언트에 메시지가 보내지도록 만들었다.

 

 

참고: https://hudi.blog/websocket-with-nodejs/

 

 

1