Skip to main content
Version: 4.x

服务器选项

Socket.IO 服务器选项

¥Socket.IO server options

以下选项影响 Socket.IO 服务器的行为。

¥The following options affect the behavior of the Socket.IO server.

adapter

默认值:require("socket.io-adapter")(内存适配器,源码见 此处

¥Default value: require("socket.io-adapter") (in-memory adapter, whose source code can be found here)

要使用的 "适配器"

¥The "Adapter" to use.

Redis 适配器 为例:

¥Example with the Redis adapter:

const { Server } = require("socket.io");
const { createAdapter } = require("@socket.io/redis-adapter");
const { createClient } = require("redis");

const pubClient = createClient({ host: "localhost", port: 6379 });
const subClient = pubClient.duplicate();

const io = new Server({
adapter: createAdapter(pubClient, subClient)
});

io.listen(3000);

cleanupEmptyChildNamespaces

v4.6.0 中添加

¥Added in v4.6.0

默认值:false

¥Default value: false

是否删除没有连接到套接字的 子命名空间

¥Whether to remove child namespaces that have no sockets connected to them.

如果你创建大量动态命名空间,则此选项可能很有用,因为每个命名空间都会创建自己的适配器实例。

¥This option might be useful if you create a lot of dynamic namespaces, since each namespace creates its own adapter instance.

启用此选项(默认情况下禁用)时,当套接字与动态命名空间断开连接并且没有其他套接字连接到该命名空间时,该命名空间将被清理,其适配器将被关闭。

¥With this option enabled (disabled by default), when a socket disconnects from a dynamic namespace and if there are no other sockets connected to it then the namespace will be cleaned up and its adapter will be closed.

connectionStateRecovery

v4.6.0 中添加

¥Added in v4.6.0

默认值:undefined

¥Default value: undefined

连接状态恢复 功能的选项:

¥The option for the Connection state recovery feature:

const io = new Server(httpServer, {
connectionStateRecovery: {
// the backup duration of the sessions and the packets
maxDisconnectionDuration: 2 * 60 * 1000,
// whether to skip middlewares upon successful recovery
skipMiddlewares: true,
}
});

如果 skipMiddlewares 选项设置为 true,那么当连接成功恢复时将跳过中间件:

¥If the skipMiddlewares option is set to true, then the middlewares will be skipped when the connection is successfully recovered:

function computeUserIdFromHeaders(headers) {
// to be implemented
}

// this middleware will be skipped if the connection is successfully recovered
io.use(async (socket, next) => {
socket.data.userId = await computeUserIdFromHeaders(socket.handshake.headers);

next();
});

io.on("connection", (socket) => {
// the userId attribute will either come:
// - from the middleware above (first connection or failed recovery)
// - from the recevery mechanism
console.log("userId", socket.data.userId);
});

connectTimeout

默认值:45000

¥Default value: 45000

断开未成功加入命名空间的客户端之前的毫秒数。

¥The number of ms before disconnecting a client that has not successfully joined a namespace.

parser

默认值:socket.io-parser

¥Default value: socket.io-parser

要使用的解析器。请参阅文档 此处

¥The parser to use. Please see the documentation here.

path

默认值:/socket.io/

¥Default value: /socket.io/

它是在服务器端捕获的路径的名称。

¥It is the name of the path that is captured on the server side.

caution

服务器和客户端值必须匹配(除非你在两者之间使用路径重写代理)。

¥The server and the client values must match (unless you are using a path-rewriting proxy in between).

服务器

¥Server

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
path: "/my-custom-path/"
});

客户端

¥Client

import { io } from "socket.io-client";

const socket = io("https://example.com", {
path: "/my-custom-path/"
});

serveClient

默认值:true

¥Default value: true

是否提供客户端文件。如果是 true,则不同的打包包将在以下位置提供:

¥Whether to serve the client files. If true, the different bundles will be served at the following location:

  • <url>/socket.io/socket.io.js

  • <url>/socket.io/socket.io.min.js

  • <url>/socket.io/socket.io.msgpack.min.js

(包括其相关的源映射)

¥(including their associated source maps)

另见 此处

¥See also here.

底层引擎选项

¥Low-level engine options

以下选项影响底层 Engine.IO 服务器的行为。

¥The following options affect the behavior of the underlying Engine.IO server.

addTrailingSlash

v4.6.0 中添加

¥Added in v4.6.0

默认值:true

¥Default value: true

默认添加的尾部斜杠现在可以禁用:

¥The trailing slash which was added by default can now be disabled:

import { createServer } from "node:http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
addTrailingSlash: false
});

在上面的示例中,客户端可以省略尾部斜杠并使用 /socket.io 而不是 /socket.io/

¥In the example above, the clients can omit the trailing slash and use /socket.io instead of /socket.io/.

allowEIO3

默认值:false

¥Default value: false

是否启用与 Socket.IO v2 客户端的兼容性。

¥Whether to enable compatibility with Socket.IO v2 clients.

也可以看看:从 2.x 迁移到 3.0

¥See also: Migrating from 2.x to 3.0

示例:

¥Example:

const io = new Server(httpServer, {
allowEIO3: true // false by default
});

allowRequest

默认:-

¥Default: -

接收给定握手或升级请求作为其第一个参数的函数,并可以决定是否继续。

¥A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not.

示例:

¥Example:

const io = new Server(httpServer, {
allowRequest: (req, callback) => {
const isOriginValid = check(req);
callback(null, isOriginValid);
}
});

这也可以与 initial_headers 事件结合使用,向客户端发送 cookie:

¥This can also be used in conjunction with the initial_headers event, to send a cookie to the client:

import { serialize } from "cookie";

const io = new Server(httpServer, {
allowRequest: async (req, callback) => {
const session = await fetchSession(req);
req.session = session;
callback(null, true);
}
});

io.engine.on("initial_headers", (headers, req) => {
if (req.session) {
headers["set-cookie"] = serialize("sid", req.session.id, { sameSite: "strict" });
}
});

也可以看看:

¥See also:

allowUpgrades

默认值:true

¥Default value: true

是否允许传输升级。

¥Whether to allow transport upgrades.

默认值:-

¥Default value: -

将转发到 cookie 模块的选项列表。可用选项:

¥The list of options that will be forwarded to the cookie module. Available options:

  • 字段

    ¥domain

  • 编码

    ¥encode

  • 过期

    ¥expires

  • 仅 http

    ¥httpOnly

  • 最大年龄

    ¥maxAge

  • 路径

    ¥path

  • 同一站点

    ¥sameSite

  • 安全的

    ¥secure

示例:

¥Example:

import { Server } from "socket.io";

const io = new Server(httpServer, {
cookie: {
name: "my-cookie",
httpOnly: true,
sameSite: "strict",
maxAge: 86400
}
});
info

从 Socket.IO v3 开始,默认情况下不再发送 cookie (reference)。

¥Since Socket.IO v3, there is no cookie sent by default anymore (reference).

cors

默认值:-

¥Default value: -

将转发到 cors 模块的选项列表。更多信息可参见 此处

¥The list of options that will be forwarded to the cors module. More information can be found here.

示例:

¥Examples:

  • 允许给定的源

    ¥allow a given origin

const io = new Server(httpServer, {
cors: {
origin: ["https://example.com"]
}
});
  • 用于本地开发的特定源

    ¥allow a given origin for local development

const io = new Server(httpServer, {
cors: {
origin: process.env.NODE_ENV === "production" ? false : ["http://localhost:3000"]
}
});
  • 允许给定的来源、标头和凭据(例如 cookie、授权标头或 TLS 客户端证书)

    ¥allow the given origins, headers and credentials (such as cookies, authorization headers or TLS client certificates)

const io = new Server(httpServer, {
cors: {
origin: ["https://example.com", "https://dev.example.com"],
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
note

如果你希望浏览器发送 cookie、授权标头或 TLS 客户端证书等凭证,你还需要在客户端将 withCredentials 选项设置为 true

¥If you want the browser to send credentials such as cookies, authorization headers or TLS client certificates, you also need to set withCredentials option to true on the client side:

import { io } from "socket.io-client";

const socket = io("https://my-backend.com", {
withCredentials: true
});

更多信息在 此处

¥More information here.

  • 允许任何源

    ¥allow any origin

const io = new Server(httpServer, {
cors: {
origin: "*"
}
});
danger

请注意,在这种情况下,你基本上禁用了跨源资源共享 (CORS) 提供的安全性,因为任何域都可以访问你的服务器。请谨慎使用。

¥Please note that in that case, you are basically disabling the security provided by Cross-Origin Resource Sharing (CORS), as any domain will be able to reach your server. Please use with caution.

可用选项:

¥Available options:

选项描述
origin配置 Access-Control-Allow-Origin CORS 标头。
methods配置 Access-Control-Allow-Methods CORS 标头。需要一个逗号分隔的字符串(例如:'GET,PUT,POST')或一个数组(例如:['GET', 'PUT', 'POST'])。
allowedHeaders配置 Access-Control-Allow-Headers CORS 标头。需要一个逗号分隔的字符串(例如:'内容类型、授权')或一个数组(例如:['Content-Type', 'Authorization'])。如果未指定,则默认反映请求的 Access-Control-Request-Headers 标头中指定的标头。
exposedHeaders配置 Access-Control-Expose-Headers CORS 标头。需要一个逗号分隔的字符串(例如:'内容范围、X 内容范围')或一个数组(例如:['Content-Range', 'X-Content-Range'])。如果未指定,则不会公开任何自定义标头。
credentials配置 Access-Control-Allow-Credentials CORS 标头。设置为 true 以传递标头,否则省略。
maxAge配置 Access-Control-Max-Age CORS 标头。设置为整数以传递标头,否则省略。
preflightContinue将 CORS 预检响应传递给下一个处理程序。
optionsSuccessStatus提供用于成功 OPTIONS 请求的状态代码,因为某些旧版浏览器(IE11、各种 SmartTV)会在 204 上阻塞。

origin 选项的可能值:

¥Possible values for the origin option:

  • Boolean - 将 origin 设置为 true 以反映 请求来源(如 req.header('Origin') 所定义),或将其设置为 false 以禁用 CORS。

    ¥Boolean - set origin to true to reflect the request origin, as defined by req.header('Origin'), or set it to false to disable CORS.

  • String - 将 origin 设置为特定原点。例如,如果将其设置为 "http://example.com",则仅允许来自“http://example.com”的请求。

    ¥String - set origin to a specific origin. For example if you set it to "http://example.com" only requests from "http://example.com" will be allowed.

  • RegExp - 将 origin 设置为将用于测试请求来源的正则表达式模式。如果匹配,将反映请求来源。例如,模式 /example\.com$/ 将反映来自以 "example.com" 结尾的来源的任何请求。

    ¥RegExp - set origin to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern /example\.com$/ will reflect any request that is coming from an origin ending with "example.com".

  • Array - 将 origin 设置为有效来源的数组。每个原点可以是 StringRegExp。例如,["http://example1.com", /\.example2\.com$/] 将接受来自“http://example1.com”或 "example2.com" 子域的任何请求。

    ¥Array - set origin to an array of valid origins. Each origin can be a String or a RegExp. For example ["http://example1.com", /\.example2\.com$/] will accept any request from "http://example1.com" or from a subdomain of "example2.com".

  • Function - 将 origin 设置为实现某些自定义逻辑的函数。该函数将请求源作为第一个参数,将回调(需要签名 err [object], allow [bool])作为第二个参数。

    ¥Function - set origin to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (which expects the signature err [object], allow [bool]) as the second.

note

即使有多个域,该选项也被命名为 origin(而不是 origins):

¥The option is named origin (and not origins) even with multiple domains:

const io = new Server(httpServer, {
cors: {
// BAD
origins: ["https://example.com"],
// GOOD
origin: ["https://example.com"],
}
});
caution

设置 credentials: true 时不能使用 origin: "*"

¥You can't use origin: "*" when setting credentials: true:

// THIS WON'T WORK
const io = new Server(httpServer, {
cors: {
origin: "*",
credentials: true
}
});

你将在浏览器控制台中看到如下错误:

¥You will see an error like this in the browser console:

跨源请求被阻止:同源策略不允许读取“.../socket.io/?EIO=4&transport=polling&t=NvQfU77”处的远程资源。(原因:如果 CORS 标头“Access-Control-Allow-Origin”为“*”,则不支持凭据)

¥Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘.../socket.io/?EIO=4&transport=polling&t=NvQfU77’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’)

你需要提供域列表(推荐解决方案)或使用以下方法:

¥You need to either provide a list of domains (recommended solution) or use the following method:

const io = new Server(httpServer, {
cors: {
origin: (_req, callback) => {
callback(null, true);
},
credentials: true
}
});

请注意,在这种情况下,就像 origin: "*"origin: true 一样,你基本上禁用了跨源资源共享 (CORS) 提供的安全性,因为任何域都可以访问你的服务器。请谨慎使用。

¥Please note that in that case, like with origin: "*" or origin: true, you are basically disabling the security provided by Cross-Origin Resource Sharing (CORS), as any domain will be able to reach your server. Please use with caution.

httpCompression

v1.4.0 中添加

¥Added in v1.4.0

默认值:true

¥Default value: true

是否启用 HTTP 长轮询传输的压缩。

¥Whether to enable the compression for the HTTP long-polling transport.

请注意,如果 httpCompression 设置为 false,则当使用 HTTP 长轮询请求建立连接时,发送时使用的压缩标志 (socket.compress(true).emit(...)) 将被忽略。

¥Please note that if httpCompression is set to false, the compress flag used when emitting (socket.compress(true).emit(...)) will be ignored when the connection is established with HTTP long-polling requests.

支持 Node.js zlib 模块 中的所有选项。

¥All options from the Node.js zlib module are supported.

示例:

¥Example:

const io = new Server(httpServer, {
httpCompression: {
// Engine.IO options
threshold: 2048, // defaults to 1024
// Node.js zlib options
chunkSize: 8 * 1024, // defaults to 16 * 1024
windowBits: 14, // defaults to 15
memLevel: 7, // defaults to 8
}
});

maxHttpBufferSize

默认值:1e6(1MB)

¥Default value: 1e6 (1 MB)

这定义了在关闭套接字之前单个消息可以有多少字节。你可以根据需要增加或减少该值。

¥This defines how many bytes a single message can be, before closing the socket. You may increase or decrease this value depending on your needs.

const io = new Server(httpServer, {
maxHttpBufferSize: 1e8
});

它与 ws 包的 maxPayload 选项匹配。

¥It matches the maxPayload option of the ws package.

perMessageDeflate

History
版本变化
v3.0.0permessage-deflate 扩展现在默认处于禁用状态。
v1.4.0首次实现。

默认值:false

¥Default value: false

是否为 WebSocket 传输启用 许可放气扩展。众所周知,此扩展会在性能和内存消耗方面增加显着的开销,因此我们建议仅在确实需要时才启用它。

¥Whether to enable the permessage-deflate extension for the WebSocket transport. This extension is known to add a significant overhead in terms of performance and memory consumption, so we suggest to only enable it if it is really needed.

请注意,如果 perMessageDeflate 设置为 false(这是默认值),则在使用 WebSocket 建立连接时,触发时使用的压缩标志 (socket.compress(true).emit(...)) 将被忽略,因为无法在每条消息上启用 permessage-deflate 扩展 基础。

¥Please note that if perMessageDeflate is set to false (which is the default), the compress flag used when emitting (socket.compress(true).emit(...)) will be ignored when the connection is established with WebSockets, as the permessage-deflate extension cannot be enabled on a per-message basis.

支持 ws 模块 的所有选项:

¥All options from the ws module are supported:

const io = new Server(httpServer, {
perMessageDeflate: {
threshold: 2048, // defaults to 1024

zlibDeflateOptions: {
chunkSize: 8 * 1024, // defaults to 16 * 1024
},

zlibInflateOptions: {
windowBits: 14, // defaults to 15
memLevel: 7, // defaults to 8
},

clientNoContextTakeover: true, // defaults to negotiated value.
serverNoContextTakeover: true, // defaults to negotiated value.
serverMaxWindowBits: 10, // defaults to negotiated value.

concurrencyLimit: 20, // defaults to 10
}
});

pingInterval

默认值:25000

¥Default value: 25000

该值用于心跳机制,定期检查服务器和客户端之间的连接是否仍然有效。

¥This value is used in the heartbeat mechanism, which periodically checks if the connection is still alive between the server and the client.

服务器每隔 pingInterval 毫秒发送一个 ping 包,如果客户端在 pingTimeout 毫秒内没有用 pong 应答,服务器认为连接已关闭。

¥The server sends a ping packet every pingInterval ms, and if the client does not answer with a pong within pingTimeout ms, the server considers that the connection is closed.

同样,如果客户端在 pingInterval + pingTimeout 毫秒内没有收到服务器发送的 ping 包,那么客户端也认为连接已关闭。

¥Similarly, if the client does not receive a ping packet from the server within pingInterval + pingTimeout ms, then the client also considers that the connection is closed.

在这两种情况下,断开连接的原因都是:ping timeout

¥In both cases, the disconnection reason will be: ping timeout

socket.on("disconnect", (reason) => {
console.log(reason); // "ping timeout"
});
caution

使用像 1000(每秒一次心跳)这样的小值会在服务器上产生一些负载,这在有数千个连接的客户端时可能会变得明显。

¥Using a small value like 1000 (one heartbeat per second) will incur some load on your server, which might become noticeable with a few thousands connected clients.

pingTimeout

History
版本变化
v4.0.0pingTimeout 现在默认为 20000 毫秒。
v2.1.0默认为 5000 毫秒。
v1.0.0默认为 60000 毫秒。

默认值:20000

¥Default value: 20000

参见 above

¥See above.

caution

使用较小的值意味着暂时无响应的服务器可能会触发大量客户端重新连接。

¥Using a smaller value means that a temporarily unresponsive server might trigger a lot of client reconnections.

相反,使用较大的值意味着需要更长的时间才能检测到断开的连接(如果 pingInterval + pingTimeout 大于 60 秒,你可能会在 React Native 上收到警告)。

¥On the contrary, using a bigger value means that a broken connection will take longer to get detected (and you might get a warning on React Native if pingInterval + pingTimeout is bigger than 60 seconds).

transports

默认值:["polling", "websocket"]

¥Default value: ["polling", "websocket"]

服务器端允许的底层传输。

¥The low-level transports that are allowed on the server-side.

启用 WebTransport 的示例:

¥Example with WebTransport enabled:

const io = new Server({
transports: ["polling", "websocket", "webtransport"]
});

请检查 WebTransport 示例 此处

¥Please check the WebTransport example here.

也可以看看:客户端 transports

¥See also: client-side transports

upgradeTimeout

默认值:10000

¥Default value: 10000

这是取消未完成的传输升级之前的延迟(以毫秒为单位)。

¥This is the delay in milliseconds before an uncompleted transport upgrade is cancelled.

wsEngine

默认值:require("ws").Server(源代码可参见 此处

¥Default value: require("ws").Server (source code can be found here)

要使用的 WebSocket 服务器实现。请参阅文档 此处

¥The WebSocket server implementation to use. Please see the documentation here.

示例:

¥Example:

const io = new Server(httpServer, {
wsEngine: require("eiows").Server
});