WebSocket实现简单聊天室。

270 阅读1分钟

笔者在学习WebSocket时,写的一个简单demo。
使用了node-websocket这个包。实现了在页面上的多人聊天功能。也不算复杂。。。

页面代码

<!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>Document</title>
</head>

<body>
    <h1>Chat Room</h1>
    <input type="text" id="sendTxt">
    <button id="sendBtn">发送</button>
    <script>
        let websocket = new WebSocket('ws://127.0.0.1:3000/');
        function showMessage(str, type) {
            let div = document.createElement('div');
            div.innerHTML = str;
            if (type === 'enter') {
                div.style.color = 'blue';
            } else if (type === 'leave') {
                div.style.color = 'red'
            }
            document.body.appendChild(div);
        }
        websocket.onopen = function () {
            console.log('websocket open');
            document.getElementById('sendBtn').onclick = function () {
                let txt = document.getElementById('sendTxt').value;
                if (txt) {
                    websocket.send(txt)
                }
            }
        }
        websocket.onclose = function () {
            console.log('websocket close');
        }
        websocket.onmessage = function (e) {
            console.log(e.data);
            let mes = JSON.parse(e.data)
            showMessage(mes.data, mes.type)
        }

    </script>
</body>

</html>

node服务

let ws = require('nodejs-websocket')

let PORT = 3000

let clientCount = 0;

let server = ws.createServer(function (conn) {
    console.log('New connection');
    clientCount++
    conn.nickname = 'user' + clientCount;
    let mes = {};
    mes.type = 'enter'
    mes.data = conn.nickname + ' comes in'
    broadcast(JSON.stringify(mes))

    conn.on('text', function (str) {
        console.log('Received' + str);
        let mes = {};
        mes.type = 'message'
        mes.data = conn.nickname + ' says: ' + str
        broadcast(JSON.stringify(mes))
    })
    conn.on('close', function (code, reason) {
        console.log('Connection closed');
        let mes = {};
        mes.type = 'leave'
        mes.data = conn.nickname + ' left'
        broadcast(JSON.stringify(mes))
    })
    conn.on('error', function (err) {
        console.log('handle err');
        console.log(err);
    })
}).listen(PORT)

console.log('websocket server listening on port ' + PORT);

function broadcast(str) {
    server.connections.forEach(function (connection) {
        connection.sendText(str)
    })
}

步骤

node wsServer.js。接下来打开不同的页面就会创建一个新的聊天室成员
会显示成员进出聊天室的信息。

image.png image.png

image.png

image.png

image.png

image.png

image.png


记录记录!