基於websocket與nodejs-websocket的簡單聊天室

jojo付啾啾發表於2018-08-16

1.專案目錄:

  • websocketChatRoom
    • index.html(客戶端)
    • wsServer.js(伺服器)

2.安裝nodejs-websocket(https://www.npmjs.com/package/nodejs-websocket

  • npm install nodejs-websocket

3.index.html

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>websocket聊天室</title>
</head>

<body>
    <input id="sendTxt" type="text">
    <button id="send">send</button>
    <script type="text/javascript">
        var websocket = new WebSocket("ws://localhost:3000/");
        websocket.onopen = function() {
            console.log("websocket open");
            // 傳送訊息放在這裡
            document.getElementById("send").onclick = function() {
                var txt = document.getElementById("sendTxt").value;
                if (txt) {
                    websocket.send(txt);
                }
            }
        }
        websocket.onclose = function() {
            console.log("websocket close");
        }
        // 只接收字串引數,所以在服務端相傳物件過來可以用JSON先轉換成字串,然後在這邊轉成物件
        websocket.onmessage = function(e) {
            console.log(e.data);
            var mes = JSON.parse(e.data);
            showMessage(mes.data, mes.type);
        }

        // 顯示訊息函式
        function showMessage(str, type) {
            var div = document.createElement('div');
            if (type == "enter") {
                div.style.color = "red";
            } else if (type == "message") {
                div.style.color = "blue";
            } else if (type == "leave") {
                div.style.color = "green";
            }
            div.innerHTML = str;
            document.body.appendChild(div);
        }
    </script>
</body>

</html>

4.wsServer.js

var ws = require("nodejs-websocket")

const PORT = 3000;

// 每進來一個客戶端就記錄一下
var clientCount = 0;

var 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 running on port: " + PORT);

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

5.執行結果

 

 

 

 

 

6.注意

  • index.html裡的onmessage回撥函式要接收字串作為引數,所以在服務端要用JSON轉換成字串,然後再在客戶端轉成物件!
  • 這裡的實現過程都是自己寫的,可以藉助socket.io來實現,它可以傳送任何型別的資料,不僅僅是字串,而且可以自定義事件

相關文章