You need to enable JavaScript to run this app. Node.js简单WebSocket代码运行内存占用过高问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Node.js简单WebSocket代码运行内存占用过高问题求助

问题根因分析
  • 内存飙升的核心原因是WebSocket消息发送的背压未处理:你调用client.send()时没有传入回调函数,也没有校验客户端缓冲区状态。当部分客户端网络不佳、接收速度慢于每秒50-60条的发送频率时,未成功发送的消息会被暂存在Node.js堆外缓冲区,这部分内存不受V8堆内存限制,所以会出现V8堆仅占用40%、但进程总RAM涨到4GB的情况。
  • 未监听WebSocket的close、error生命周期事件:异常断开的连接不会被自动从wss.clients集合中移除,广播时会持续给无效连接尝试发消息,进一步加剧缓冲区内存堆积。
  • 广播逻辑效率低下:每次发消息都全量遍历所有客户端,每秒产生上千次无效判断,累积的I/O队列也会占用额外内存。
  • 代码存在未捕获异常隐患:express路由中未引入path模块就调用path.join,且单次请求连续调用两次res.sendFile,异常上下文残留也会占用不必要的内存。
修复方案

修复后完整代码

const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
const path = require('path');
const url = require('url');
const WebSocketServer = require('ws').Server;

const app = express();

// 证书配置
const privateKey = fs.readFileSync('/etc/letsencrypt/live/domainnanem/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/domainnanem/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/domainnanem/chain.pem', 'utf8');
const credentials = {
    key: privateKey,
    cert: certificate,
    ca: ca
};

// 修复express路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'html', 'index.html'));
});
app.get('/app.js', (req, res) => {
    res.sendFile(path.join(__dirname, 'app.js'));
});

const httpsServer = https.createServer(credentials, app);
httpsServer.listen(9992, () => {
    console.log('HTTPS Server running on port 9992');
});

// 按房间维护客户端集合,避免全量遍历
const roomClients = new Map();

const wss = new WebSocketServer({
    server: httpsServer
});

wss.on('connection', function (ws, req) {
    const { query: { token } } = url.parse(req.url, true);
    ws.room = token;

    // 加入对应房间集合
    if (!roomClients.has(ws.room)) {
        roomClients.set(ws.room, new Set());
    }
    roomClients.get(ws.room).add(ws);

    // 监听消息,优化广播逻辑
    ws.on('message', function (message) {
        const clients = roomClients.get(ws.room);
        if (!clients) return;
        clients.forEach(function each(client) {
            if (client.readyState === ws.OPEN) {
                // 缓冲区超过256KB时断开慢客户端,避免内存堆积
                if (client.bufferedAmount > 256 * 1024) {
                    client.terminate();
                    return;
                }
                // 加回调处理发送错误
                client.send(message, (err) => {
                    if (err) client.terminate();
                });
            }
        });
    });

    // 补全断开/错误事件监听,清理资源
    ws.on('close', () => {
        const clients = roomClients.get(ws.room);
        if (clients) {
            clients.delete(ws);
            if (clients.size === 0) {
                roomClients.delete(ws.room);
            }
        }
    });
    ws.on('error', (err) => {
        ws.terminate();
    });
});

额外优化建议

  • 可在PM2配置中添加max_memory_restart参数,设置阈值为1GB,避免内存溢出影响业务
  • 单条10KB的消息每秒广播60次,可对重复消息做二进制压缩进一步降低传输开销

内容的提问来源于stack exchange,提问作者Savsoft Technologies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 06:06:07