Engine

The Engine.IO server, which manages the WebSocket / HTTP long-polling connections. More information here.

Its source code can be found here: https://github.com/socketio/engine.io

engine.clientsCount

Added in v1.0.0

The number of currently connected clients.

  1. const count = io.engine.clientsCount;
    // may or may not be similar to the count of Socket instances in the main namespace, depending on your usage
    const count2 = io.of("/").sockets.size;

engine.generateId

The function used to generate a new session ID. Defaults to base64id.

  1. const uuid = require("uuid");

    io.engine.generateId = () => {
    return uuid.v4(); // must be unique across all Socket.IO servers
    }

engine.handleUpgrade(request, socket, head)

Added in v1.0.0

This method can be used to inject an HTTP upgrade:

Example with both a Socket.IO server and a plain WebSocket server:

  1. const { createServer } = require("http");
    const ws = require("ws");
    const { Server } = require("socket.io");

    const httpServer = createServer();
    const wss = new ws.Server({ noServer: true });
    const io = new Server(httpServer);

    httpServer.removeAllListeners("upgrade");

    httpServer.on("upgrade", (req, socket, head) => {
    if (req.url === "/") {
    wss.handleUpgrade(req, socket, head, (ws) => {
    wss.emit("connection", ws, req);
    });
    } else if (req.url.startsWith("/socket.io/")) {
    io.engine.handleUpgrade(req, socket, head);
    } else {
    socket.destroy();
    }
    });

    httpServer.listen(3000);

Event: ‘initial_headers’

Added in v4.1.0

This event will be emitted just before writing the response headers of the first HTTP request of the session (the handshake), allowing you to customize them.

  1. io.engine.on("initial_headers", (headers, request) => {
    headers["test"] = "123";
    headers["set-cookie"] = "mycookie=456";
    });

Event: ‘headers’

Added in v4.1.0

This event will be emitted just before writing the response headers of each HTTP request of the session (including the WebSocket upgrade), allowing you to customize them.

  1. io.engine.on("headers", (headers, request) => {
    headers["test"] = "789";
    });

Event: ‘connection_error’

Added in v4.1.0

  1. io.engine.on("connection_error", (err) => {
    console.log(err.req); // the request object
    console.log(err.code); // the error code, for example 1
    console.log(err.message); // the error message, for example "Session ID unknown"
    console.log(err.context); // some additional error context
    });

This event will be emitted when a connection is abnormally closed. Here is the list of possible error codes:

CodeMessage
0“Transport unknown”
1“Session ID unknown”
2“Bad handshake method”
3“Bad request”
4“Forbidden”
5“Unsupported protocol version”

Caught a mistake? Edit this page on GitHub