nodejs-websocket简易聊天室实例

1.下载安装nodejs-websocket

cnpm install nodejs-websocket

2.编写index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocket示例</title>
</head>
<body>
<h1>简易聊天室</h1>
<input id="sendTxt" type="text" />
<button id="sendBtn">发送</button>
<script>
    var websocket = new WebSocket('ws://localhost:8001/');
    function showMessage(str){
        var div = document.createElement('div');
        div.innerHTML = str;
        document.body.appendChild(div);
    }
    //建立连接
    websocket.onopen = function(){
        console.log('websocket连接打开');
        document.getElementById('sendBtn').onclick = function(){
            var txt = document.getElementById('sendTxt').value;
            if(txt){
                websocket.send(txt);  //发送数据给服务器
                document.getElementById('sendTxt').value = '';
            }
        }
    };
    //关闭连接
    websocket.onclose==function(){
        console.log('关闭Websocket连接');
    }
    //客户端接收数据触发
    websocket.onmessage = function(e){
        console.log(e.data);
        showMessage(e.data);
    }
</script>
</body>
</html>


3.编写server.js
var ws = require("nodejs-websocket");
var clientCount = 0;

var server = ws.createServer(function (conn) {
    console.log("新建连接");
    clientCount++;
    conn.nickname='用户'+clientCount;
    boradcast(conn.nickname+'进入聊天室');
    //服务端接收到消息后触发
    conn.on("text", function (str) {
        boradcast(conn.nickname+': '+str);
    });
    //关闭连接
    conn.on("close", function (code, reason) {
        console.log("连接关闭");
        boradcast(conn.nickname+'离开聊天室');
    });
    //
    conn.on("error",function(err){
        console.log("发生错误");
        console.log(err);
    })
}).listen(8001);

function boradcast(str){
    server.connections.forEach(function(connection){
        connection.sendText(str);
    })
}
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注