豫ICP备2024044691号-1
powered by emlog
node.js搭建websocket服务
Mins 2022-3-18 00:36 node

相对于 php 和 Python 来说,使用 node 搭建 websocket 服务非常简单,刚刚折腾了一下,做个笔录,不是,是记录。。。

// 引入ws模块
const WebSocket = require('ws');

// 服务器
const ws = new WebSocket.Server({ port: 5000 }, function (){
    console.log('Socket Server Is Running at 5000...')
})

// 客户端连接池
let clients = [];

// 单个客户端连接
const setClient = (c) => {

    // 客户端唯一标识
    let id = clients.length + 1;

    // 客户端信息
    let client = { id, c, time: parseInt(new Date().getTime()) };

    // 保存进连接池
    clients.push(client);

    // 连接成功,返回欢迎信息
    c.send('welcome. your id is: ' + id);

    // 监听客户端消息
    c.on('message', function (msg){
        console.log(`id-${id} say: ` + msg);
    })

    // 客户端关闭连接时,释放当前连接的内存
    c.on('close', function (){
        echo(`id-${id} is closed`);
        for(let i=0; i<clients.length; i++) if(clients[i] && clients[i].id == id) clients[i] = null;
    })
}

// 监听连接
ws.on('connection', function (c){
    setClient(c);
})

// 主动推消息
const send = (id, msg) => {
    for(let i=0; i<clients.length; i++) if(clients[i] && clients[i].id == id) clients[i].c.send(msg);
}

// 例如:给ID为 1 的客户端发送 “你好”
send(1, '你好'); 

以上。并发相关的东西还在摸索,暂时不写。但是需要注意的是,当客户端关闭连接时,释放内存的操作并没有很明显的内存掉落效果,这是个很重要的坑,需要花时间填上。