客户端配置

IO factory options

forceNew

Default value: false

Whether to create a new Manager instance.

A Manager instance is in charge of the low-level connection to the server (established with HTTP long-polling or WebSocket). It handles the reconnection logic.

A Socket instance is the interface which is used to sends events to — and receive events from — the server. It belongs to a given namespace.

A single Manager can be attached to several Socket instances.

The following example will reuse the same Manager instance for the 3 Socket instances (one single WebSocket connection):

  1. const socket = io("https://example.com"); // the main namespace
  2. const productSocket = io("https://example.com/product"); // the "product" namespace
  3. const orderSocket = io("https://example.com/order"); // the "order" namespace

The following example will create 3 different Manager instances (and thus 3 distinct WebSocket connections):

  1. const socket = io("https://example.com"); // the main namespace
  2. const productSocket = io("https://example.com/product", { forceNew: true }); // the "product" namespace
  3. const orderSocket = io("https://example.com/order", { forceNew: true }); // the "order" namespace

Reusing an existing namespace will also create a new Manager each time:

  1. const socket1 = io(); // 1st manager
  2. const socket2 = io(); // 2nd manager
  3. const socket3 = io("/admin"); // reuse the 1st manager
  4. const socket4 = io("/admin"); // 3rd manager

multiplex

Default value: true

The opposite of forceNew: whether to reuse an existing Manager instance.

  1. const socket = io(); // 1st manager
  2. const adminSocket = io("/admin", { multiplex: false }); // 2nd manager

Low-level engine options

客户端配置 - 图1信息

These settings will be shared by all Socket instances attached to the same Manager.

transports

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

The low-level connection to the Socket.IO server can either be established with:

  • HTTP long-polling: successive HTTP requests (POST for writing, GET for reading)
  • WebSocket

The following example disables the HTTP long-polling transport:

  1. const socket = io("https://example.com", { transports: ["websocket"] });

Note: in that case, sticky sessions are not required on the server side (more information here).

By default, the HTTP long-polling connection is established first, and then an upgrade to WebSocket is attempted (explanation here). You can use WebSocket first with:

  1. const socket = io("https://example.com", {
  2. transports: ["websocket", "polling"] // use WebSocket first, if available
  3. });
  4. socket.on("connect_error", () => {
  5. // revert to classic upgrade
  6. socket.io.opts.transports = ["polling", "websocket"];
  7. });

One possible downside is that the validity of your CORS configuration will only be checked if the WebSocket connection fails to be established.

upgrade

Default value: true

Whether the client should try to upgrade the transport from HTTP long-polling to something better.

rememberUpgrade

Default value: false

If true and if the previous WebSocket connection to the server succeeded, the connection attempt will bypass the normal upgrade process and will initially try WebSocket. A connection attempt following a transport error will use the normal upgrade process. It is recommended you turn this on only when using SSL/TLS connections, or if you know that your network does not block websockets.

path

Default value: /socket.io/

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

客户端配置 - 图2警告

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

Client

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

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. });

Please note that this is different from the path in the URI, which represents the Namespace.

Example:

  1. import { io } from "socket.io-client";
  2. const socket = io("https://example.com/order", {
  3. path: "/my-custom-path/"
  4. });
  • the Socket instance is attached to the “order” Namespace
  • the HTTP requests will look like: GET https://example.com/my-custom-path/?EIO=4&transport=polling&t=ML4jUwU

query

Default value: -

Additional query parameters (then found in socket.handshake.query object on the server-side).

Example:

Client

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. query: {
  4. x: 42
  5. }
  6. });

Server

  1. io.on("connection", (socket) => {
  2. console.log(socket.handshake.query); // prints { x: "42", EIO: "4", transport: "polling" }
  3. });

The query parameters cannot be updated for the duration of the session, so changing the query on the client-side will only be effective when the current session gets closed and a new one is created:

  1. socket.io.on("reconnect_attempt", () => {
  2. socket.io.opts.query.x++;
  3. });

Note: the following query parameters are reserved and can’t be used in your application:

  • EIO: the version of the protocol (currently, “4”)
  • transport: the transport name (“polling” or “websocket”)
  • sid: the session ID
  • j: if the transport is polling but a JSONP response is required
  • t: a hashed-timestamp used for cache-busting

extraHeaders

Default value: -

Additional headers (then found in socket.handshake.headers object on the server-side).

Example:

Client

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. extraHeaders: {
  4. "my-custom-header": "1234"
  5. }
  6. });

Server

  1. io.on("connection", (socket) => {
  2. console.log(socket.handshake.headers); // an object containing "my-custom-header": "1234"
  3. });

客户端配置 - 图3警告

In a browser environment, the extraHeaders option will be ignored if you only enable the WebSocket transport, since the WebSocket API in the browser does not allow providing custom headers.

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. transports: ["websocket"],
  4. extraHeaders: {
  5. "my-custom-header": "1234" // ignored
  6. }
  7. });

This will work in Node.js or in React-Native though.

Documentation: WebSocket API

withCredentials

History

VersionChanges
v4.7.0The Node.js client now honors the withCredentials setting.
v3.0.0withCredentials now defaults to false.
v1.0.0First implementation.

Default value: false

Whether the cross-site requests should be sent including credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.

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

The server needs to send the right Access-Control-Allow-* headers to allow the connection:

  1. import { createServer } from "http";
  2. import { Server } from "socket.io";
  3. const httpServer = createServer();
  4. const io = new Server(httpServer, {
  5. cors: {
  6. origin: "https://my-frontend.com",
  7. credentials: true
  8. }
  9. });

客户端配置 - 图4警告

You cannot use origin: * when setting withCredentials to true. This will trigger the following error:

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 ‘*’)

Documentation:

客户端配置 - 图5信息

Starting with version 4.7.0, when setting the withCredentials option to true, the Node.js client will now include the cookies in the HTTP requests, making it easier to use it with cookie-based sticky sessions.

forceBase64

Default value: false

Whether to force base64 encoding for binary content sent over WebSocket (always enabled for HTTP long-polling).

timestampRequests

Default value: true

Whether to add the timestamp query param to each request (for cache busting).

timestampParam

Default value: "t"

The name of the query parameter to use as our timestamp key.

closeOnBeforeunload

Added in v4.1.0

Default value: true

Whether to (silently) close the connection when the beforeunload event is emitted in the browser.

With closeOnBeforeunload set to false, a disconnect event will be emitted by the Socket instance when the user reloads the page on Firefox (but not on Chrome or Safari).

With closeOnBeforeunload set to true, all browsers will have the same behavior (no disconnect event when reloading the page). But this might cause issues if you use the beforeunload event in your application.

protocols

Added in v2.0.0

Default value: -

Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol).

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. transports: ["websocket"],
  4. protocols: ["my-protocol-v1"]
  5. });

Server:

  1. io.on("connection", (socket) => {
  2. const transport = socket.conn.transport;
  3. console.log(transport.socket.protocol); // prints "my-protocol-v1"
  4. });

References:

autoUnref

Added in v4.0.0

Default value: false

With autoUnref set to true, the Socket.IO client will allow the program to exit if there is no other active timer/TCP socket in the event system (even if the client is connected):

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. autoUnref: true
  4. });

See also: https://nodejs.org/api/timers.html#timeoutunref

Node.js-specific options

The following options are supported:

  • agent
  • pfx
  • key
  • passphrase
  • cert
  • ca
  • ciphers
  • rejectUnauthorized

Please refer to the Node.js documentation:

Example with a self-signed certificate:

Client

  1. import { readFileSync } from "fs";
  2. import { io } from "socket.io-client";
  3. const socket = io("https://example.com", {
  4. ca: readFileSync("./cert.pem")
  5. });

Server

  1. import { readFileSync } from "fs";
  2. import { createServer } from "https";
  3. import { Server } from "socket.io";
  4. const httpServer = createServer({
  5. cert: readFileSync("./cert.pem"),
  6. key: readFileSync("./key.pem")
  7. });
  8. const io = new Server(httpServer);

Example with client-certificate authentication:

Client

  1. import { readFileSync } from "fs";
  2. import { io } from "socket.io-client";
  3. const socket = io("https://example.com", {
  4. ca: readFileSync("./server-cert.pem"),
  5. cert: readFileSync("./client-cert.pem"),
  6. key: readFileSync("./client-key.pem"),
  7. });

Server

  1. import { readFileSync } from "fs";
  2. import { createServer } from "https";
  3. import { Server } from "socket.io";
  4. const httpServer = createServer({
  5. cert: readFileSync("./server-cert.pem"),
  6. key: readFileSync("./server-key.pem"),
  7. requestCert: true,
  8. ca: [
  9. readFileSync("client-cert.pem")
  10. ]
  11. });
  12. const io = new Server(httpServer);

客户端配置 - 图6警告

rejectUnauthorized is a Node.js-only option, it will not bypass the security check in the browser:

Security warning in the browser

Manager options

客户端配置 - 图8信息

These settings will be shared by all Socket instances attached to the same Manager.

reconnection

Default value: true

Whether reconnection is enabled or not. If set to false, you need to manually reconnect:

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. reconnection: false
  4. });
  5. const tryReconnect = () => {
  6. setTimeout(() => {
  7. socket.io.open((err) => {
  8. if (err) {
  9. tryReconnect();
  10. }
  11. });
  12. }, 2000);
  13. }
  14. socket.io.on("close", tryReconnect);

reconnectionAttempts

Default value: Infinity

The number of reconnection attempts before giving up.

reconnectionDelay

Default value: 1000

The initial delay before reconnection in milliseconds (affected by the randomizationFactor value).

reconnectionDelayMax

Default value: 5000

The maximum delay between two reconnection attempts. Each attempt increases the reconnection delay by 2x.

randomizationFactor

Default value: 0.5

The randomization factor used when reconnecting (so that the clients do not reconnect at the exact same time after a server crash, for example).

Example with the default values:

  • 1st reconnection attempt happens between 500 and 1500 ms (1000 * 2^0 * (<something between -0.5 and 1.5>))
  • 2nd reconnection attempt happens between 1000 and 3000 ms (1000 * 2^1 * (<something between -0.5 and 1.5>))
  • 3rd reconnection attempt happens between 2000 and 5000 ms (1000 * 2^2 * (<something between -0.5 and 1.5>))
  • next reconnection attempts happen after 5000 ms

timeout

Default value: 20000

The timeout in milliseconds for each connection attempt.

autoConnect

Default value: true

Whether to automatically connect upon creation. If set to false, you need to manually connect:

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. autoConnect: false
  4. });
  5. socket.connect();
  6. // or
  7. socket.io.open();

parser

Added in v2.2.0

Default value: require("socket.io-parser")

The parser used to marshall/unmarshall packets. Please see here for more information.

Socket options

客户端配置 - 图9信息

These settings are specific to the given Socket instance.

auth

Added in v3.0.0

Default value: -

Credentials that are sent when accessing a namespace (see also here).

Example:

Client

  1. import { io } from "socket.io-client";
  2. const socket = io({
  3. auth: {
  4. token: "abcd"
  5. }
  6. });
  7. // or with a function
  8. const socket = io({
  9. auth: (cb) => {
  10. cb({ token: localStorage.token })
  11. }
  12. });

Server

  1. io.on("connection", (socket) => {
  2. console.log(socket.handshake.auth); // prints { token: "abcd" }
  3. });

You can update the auth map when the access to the Namespace is denied:

  1. socket.on("connect_error", (err) => {
  2. if (err.message === "invalid credentials") {
  3. socket.auth.token = "efgh";
  4. socket.connect();
  5. }
  6. });

Or manually force the Socket instance to reconnect:

  1. socket.auth.token = "efgh";
  2. socket.disconnect().connect();