服务器配置

Socket.IO server options

path

Default value: /socket.io/

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

服务器配置 - 图1警告

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

Server

  1. import { createServer } from "http";
  2. import { Server } from "socket.io";
  3. const httpServer = createServer();
  4. const io = new Server(httpServer, {
  5. path: "/my-custom-path/"
  6. });

Client

  1. import { io } from "socket.io-client";
  2. const socket = io("https://example.com", {
  3. path: "/my-custom-path/"
  4. });

serveClient

Default value: 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.

adapter

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

The “Adapter” to use.

Example with the Redis adapter:

  • CommonJS
  • ES modules
  • TypeScript
  1. const { Server } = require("socket.io");
  2. const { createAdapter } = require("@socket.io/redis-adapter");
  3. const { createClient } = require("redis");
  4. const pubClient = createClient({ host: "localhost", port: 6379 });
  5. const subClient = pubClient.duplicate();
  6. const io = new Server({
  7. adapter: createAdapter(pubClient, subClient)
  8. });
  9. io.listen(3000);
  1. import { Server } from "socket.io";
  2. import { createAdapter } from "@socket.io/redis-adapter";
  3. import { createClient } from "redis";
  4. const pubClient = createClient({ host: "localhost", port: 6379 });
  5. const subClient = pubClient.duplicate();
  6. const io = new Server({
  7. adapter: createAdapter(pubClient, subClient)
  8. });
  9. io.listen(3000);
  1. import { Server } from "socket.io";
  2. import { createAdapter } from "@socket.io/redis-adapter";
  3. import { createClient } from "redis";
  4. const pubClient = createClient({ host: "localhost", port: 6379 });
  5. const subClient = pubClient.duplicate();
  6. const io = new Server({
  7. adapter: createAdapter(pubClient, subClient)
  8. });
  9. io.listen(3000);

parser

Default value: socket.io-parser

The parser to use. Please see the documentation here.

connectTimeout

Default value: 45000

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

Low-level engine options

pingTimeout

Default value: 20000

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

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

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

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

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

Note: the default value might be a bit low if you need to send big files in your application. Please increase it if that’s the case:

  1. const io = new Server(httpServer, {
  2. pingTimeout: 30000
  3. });

pingInterval

Default value: 25000

See above.

upgradeTimeout

Default value: 10000

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

maxHttpBufferSize

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.

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

It matches the maxPayload option of the ws package.

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:

  1. const io = new Server(httpServer, {
  2. allowRequest: (req, callback) => {
  3. const isOriginValid = check(req);
  4. callback(null, isOriginValid);
  5. }
  6. });

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

  1. import { serialize } from "cookie";
  2. const io = new Server(httpServer, {
  3. allowRequest: async (req, callback) => {
  4. const session = await fetchSession(req);
  5. req.session = session;
  6. callback(null, true);
  7. }
  8. });
  9. io.engine.on("initial_headers", (headers, req) => {
  10. if (req.session) {
  11. headers["set-cookie"] = serialize("sid", req.session.id, { sameSite: "strict" });
  12. }
  13. });

See also:

transports

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

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

See also: client-side transports

allowUpgrades

Default value: true

Whether to allow transport upgrades.

perMessageDeflate

History

VersionChanges
v3.0.0The permessage-deflate extension is now disabled by default.
v1.4.0First implementation.

Default value: false

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.

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.

All options from the ws module are supported:

  1. const io = new Server(httpServer, {
  2. perMessageDeflate: {
  3. threshold: 2048, // defaults to 1024
  4. zlibDeflateOptions: {
  5. chunkSize: 8 * 1024, // defaults to 16 * 1024
  6. },
  7. zlibInflateOptions: {
  8. windowBits: 14, // defaults to 15
  9. memLevel: 7, // defaults to 8
  10. },
  11. clientNoContextTakeover: true, // defaults to negotiated value.
  12. serverNoContextTakeover: true, // defaults to negotiated value.
  13. serverMaxWindowBits: 10, // defaults to negotiated value.
  14. concurrencyLimit: 20, // defaults to 10
  15. }
  16. });

httpCompression

Added in v1.4.0

Default value: true

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

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.

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

Example:

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

wsEngine

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

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

Example:

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

cors

Default value: -

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

Example:

  1. const io = new Server(httpServer, {
  2. cors: {
  3. origin: ["https://example.com", "https://dev.example.com"],
  4. allowedHeaders: ["my-custom-header"],
  5. credentials: true
  6. }
  7. });

Default value: -

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

  • domain
  • encode
  • expires
  • httpOnly
  • maxAge
  • path
  • sameSite
  • secure

Example:

  1. import { Server } from "socket.io";
  2. const io = new Server(httpServer, {
  3. cookie: {
  4. name: "my-cookie",
  5. httpOnly: true,
  6. sameSite: "strict",
  7. maxAge: 86400
  8. }
  9. });

服务器配置 - 图2信息

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

allowEIO3

Default value: false

Whether to enable compatibility with Socket.IO v2 clients.

See also: Migrating from 2.x to 3.0

Example:

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