NodeJS+ws模块实现websocket通讯

1.安装需要的模块

cnpm install -S express ws

2.创建server.js

var express = require('express');
var app = express();
var server = require('http').Server(app);
var websocket = require('ws');

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

var wss = new websocket.Server({
    server
});

//广播  
wss.broadcast = function broadcast(s, ws) {
    wss.clients.forEach(function each(client) {
        if (s == 1) {
            client.send(ws.name + ":" + ws.msg);
        }
        if (s == 0) {
            client.send(ws + "退出聊天室");
        }
    });
};
// 初始化连接
wss.on('connection', function(ws) {
    ws.send('你是第' + wss.clients.size + '位');
    // 接收消息并发送到客户端  
    ws.on('message', function(jsonStr, flags) {
        var obj = eval('(' + jsonStr + ')');
        this.user = obj;
        if (typeof this.user.msg != "undefined") {
            wss.broadcast(1, obj);
        }
    });
    // 退出聊天  
    ws.on('close', function(close) {
        try {
            //手动退出
            wss.broadcast(0, this.user.name);
        } catch (e) {
            console.log('连接断开');
        }
    });
});



server.listen(4000, function() {
    console.log('listening on *:4000');
});

3.新建index.html页面:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>聊天</title>
    <link rel="stylesheet" href="">
    <script language="JavaScript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
    <script type="text/javascript">
    </script>
</head>
<style type="text/css" media="screen">

</style>

<body>
    <div style="width: 500px">
        <div id="show" style="height: 100px;width: 100%; overflow-x: auto; border: 1px solid #ccc;margin-bottom: 10px;">
        </div>
        <div style="float:left">
            <label>用户:</label>
            <label name="uname" style="display: inline; width: 200px;"></label>
            <label for="message" style="margin-left: 20px;">内容:</label>
            <input type="text" name="message" id="message">
        </div>
        <div style="float: right">
            <a href="javascript:void(0)" id="send">发送</a>
            <a href="javascript:void(0)" id="exit">退出</a>
        </div>
    </div>
</body>
<script type="text/javascript">
    var uname = "";
    while (!uname) {
        uname = prompt('请输入用户名');
    }
    $('[name="uname"]').text(uname);

    var ws = new WebSocket("ws://127.0.0.1:4000");
    ws.onopen = function() {
        console.log("连接状态", ws);
        $("#show").html("连接状态;" + !!ws.readyState + "</br>");
        console.log("open");
    };
    ws.onmessage = function(evt) {
        $("#show").append(evt.data + "</br>");
    };
    ws.onclose = function(evt) {
        console.log("WebSocketClosed!");
        console.log(evt);
    };
    ws.onerror = function(evt) {
        console.log("WebSocketError!");
    };

    $('#send').on('click', _ => {
        var msg = $("#message").val();
        var name = uname;
        var str = "{name:'" + name + "',msg:'" + msg + "'}";
        console.log("发送", str);
        ws.send(str);
    });

    $('#exit').on('click', _ => {
        var r = ws.close();
        console.log("退出", r);
    })
</script>

</html>

参考地址:

Comments