npm 安装 websocket 包

服务端代码

  1. 新建一个 js 文件,如: ws_server.js
  2. 引入 websocket 包,并且 new 一个 websocket server
    1
    2
    var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 9999});
  3. 定义一个数组用来存放连接的用户
    1
    2
    // 连接池
    var clients = [];
  4. 监听 wss ,当有用户加入时,把该用户加入连接池,当某个用户发送消息当时候,循环连接池,把消息推送给每一位用户,当用户退出时,将其移出连接池
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    wss.on('connection', function (ws) {
    // 将该连接加入连接池
    clients.push(ws);
    ws.on('message', function (message) {
    console.log(message);
    // 广播消息
    clients.forEach(function (ws1) {
    if (ws1 !== ws) {
    ws1.send(message);
    }
    })
    });

    ws.on('close', function (message) {
    // 连接关闭时,将其移出连接池
    clients = clients.filter(function (ws1) {
    return ws1 !== ws
    })
    });
    });
  5. 使用 node 启动该服务
    1
    node ws_server.js

客户端代码

  1. 新建一个 a.html 文件,代码如下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <input type="text" id="text">
    <input type="button" onclick="sendMessage()" value="online">
    <div id="content"></div>

    <script>
    // x.x.x.x 改为服务器 IP)
    var ws = new WebSocket("ws://x.x.x.x:9999");

    ws.onopen = function (e) {
    console.log('Connection to server opened');
    };
    ws.onmessage = function (event) {
    console.log('Client received a message', event);
    document.getElementById('content').insertAdjacentHTML('beforeend', event.data + '<br>')
    };
    ws.onclose = function (e) {
    console.log('connection closed.');
    };

    function sendMessage() {
    document.getElementById('content').insertAdjacentHTML('beforeend', '粥粥:' + document.getElementById('text').value + '<br>');
    ws.send('粥粥:' + document.getElementById('text').value);
    document.getElementById('text').value = '';
    }
    </script>
    </body>
    </html>
  2. 新建一个 b.html 文件,代码同 a.html,此时当用户 a 打开 a.html,用户 b 打开 b.html 时,a 和 b 即可进行通信。