内存使用情况
Socket.IO 服务器消耗的资源主要取决于:
¥The resources consumed by your Socket.IO server will mainly depend on:
连接的客户端数量
¥the number of connected clients
¥the number of messages (basic emit, emit with acknowledgement and broadcast) received and sent per second
Socket.IO 服务器的内存使用量应与连接的客户端数量成线性比例。
¥The memory usage of the Socket.IO server should scale linearly with the number of connected clients.
默认情况下,每个会话的第一个 HTTP 请求的引用都保存在内存中。例如,在使用 express-session
时需要此引用(请参阅 此处),但可以将其丢弃以节省内存:
¥By default, a reference to the first HTTP request of each session is kept in memory. This reference is needed when working with express-session
for example (see here), but can be discarded to save memory:
io.engine.on("connection", (rawSocket) => {
rawSocket.request = null;
});
可以找到重现本页中显示的结果的源代码 there。
¥The source code to reproduce the results presented in this page can be found there.
也可以看看:
¥See also:
每个 WebSocket 服务器实现的内存使用情况
¥Memory usage per WebSocket server implementation
Socket.IO 服务器的内存使用情况在很大程度上取决于底层 WebSocket 服务器实现的内存使用情况。
¥The memory usage of the Socket.IO server heavily depends on the memory usage of the underlying WebSocket server implementation.
下图显示了 Socket.IO 服务器的内存使用情况(从 0 到 10 000 个连接的客户端):
¥The chart below displays the memory usage of the Socket.IO server, from 0 up to 10 000 connected clients, with:
基于
ws
包的 Socket.IO 服务器(默认使用)¥a Socket.IO server based on the
ws
package (used by default)基于
eiows
包的 Socket.IO 服务器,C++ WebSocket 服务器实现(参见 安装步骤)¥a Socket.IO server based on the
eiows
package, a C++ WebSocket server implementation (see installation steps)基于
µWebSockets.js
包的 Socket.IO 服务器,Node.js 原生 HTTP 服务器的 C++ 替代品(参见 安装步骤)¥a Socket.IO server based on the
µWebSockets.js
package, a C++ alternative to the Node.js native HTTP server (see installation steps)基于
ws
包的普通 WebSocket 服务器¥a plain WebSocket server based on the
ws
package
使用 Node.js v20.3.0
在 Ubuntu 22.04 LTS
上进行测试,具有以下软件包版本:
¥Tested on Ubuntu 22.04 LTS
with Node.js v20.3.0
, with the following package versions:
socket.io@4.7.2
eiows@6.7.2
uWebSockets.js@20.33.0
ws@8.11.0
随着时间的推移内存使用情况
¥Memory usage over time
下图显示了 Socket.IO 服务器随时间变化的内存使用情况(从 0 到 10 000 个连接的客户端)。
¥The chart below displays the memory usage of the Socket.IO server over time, from 0 up to 10 000 connected clients.
出于演示目的,我们在每波客户端结束时手动调用垃圾收集器:
¥For demonstration purposes, we manually call the garbage collector at the end of each wave of clients:
io.on("connection", (socket) => {
socket.on("disconnect", () => {
const lastToDisconnect = io.of("/").sockets.size === 0;
if (lastToDisconnect) {
gc();
}
});
});
这解释了当最后一个客户端断开连接时内存使用量的明显下降。这在你的应用中是不需要的,垃圾收集将在必要时自动触发。
¥Which explains the clean drop in memory usage when the last client disconnects. This is not needed in your application, the garbage collection will be automatically triggered when necessary.