The Socket.IO protocol

This document describes the 5th version of the Socket.IO protocol.

The source of this document can be found here.

Table of content

Introduction

The Socket.IO protocol enables full-duplex#FULL-DUPLEX) and low-overhead communication between a client and a server.

It is built on top of the Engine.IO protocol, which handles the low-level plumbing with WebSocket and HTTP long-polling.

The Socket.IO protocol adds the following features:

Example with the JavaScript API:

Server

  1. // declare the namespace
  2. const namespace = io.of("/admin");
  3. // handle the connection to the namespace
  4. namespace.on("connection", (socket) => {
  5. // ...
  6. });

Client

  1. // reach the main namespace
  2. const socket1 = io();
  3. // reach the "/admin" namespace (with the same underlying WebSocket connection)
  4. const socket2 = io("/admin");
  5. // handle the connection to the namespace
  6. socket2.on("connect", () => {
  7. // ...
  8. });
  • acknowledgement of packets

Example with the JavaScript API:

  1. // on one side
  2. socket.emit("hello", "foo", (arg) => {
  3. console.log("received", arg);
  4. });
  5. // on the other side
  6. socket.on("hello", (arg, ack) => {
  7. ack("bar");
  8. });

The reference implementation is written in TypeScript:

Exchange protocol

A Socket.IO packet contains the following fields:

  • a packet type (integer)
  • a namespace (string)
  • optionally, a payload (Object | Array)
  • optionally, an acknowledgment id (integer)

Here is the list of available packet types:

TypeIDUsage
CONNECT0Used during the connection to a namespace.
DISCONNECT1Used when disconnecting from a namespace.
EVENT2Used to send data to the other side.
ACK3Used to acknowledge an event.
CONNECT_ERROR4Used during the connection to a namespace.
BINARY_EVENT5Used to send binary data to the other side.
BINARY_ACK6Used to acknowledge an event (the response includes binary data).

Connection to a namespace

At the beginning of a Socket.IO session, the client MUST send a CONNECT packet:

The server MUST respond with either:

  • a CONNECT packet if the connection is successful, with the session ID in the payload
  • or a CONNECT_ERROR packet if the connection is not allowed
  1. CLIENT SERVER
  2. ───────────────────────────────────────────────────────►
  3. { type: CONNECT, namespace: "/" }
  4. ◄───────────────────────────────────────────────────────
  5. { type: CONNECT, namespace: "/", data: { sid: "..." } }

If the server does not receive a CONNECT packet first, then it MUST close the connection immediately.

A client MAY be connected to multiple namespaces at the same time, with the same underlying WebSocket connection.

Examples:

  • with the main namespace (named "/")
  1. Client > { type: CONNECT, namespace: "/" }
  2. Server > { type: CONNECT, namespace: "/", data: { sid: "wZX3oN0bSVIhsaknAAAI" } }
  • with a custom namespace
  1. Client > { type: CONNECT, namespace: "/admin" }
  2. Server > { type: CONNECT, namespace: "/admin", data: { sid: "oSO0OpakMV_3jnilAAAA" } }
  • with an additional payload
  1. Client > { type: CONNECT, namespace: "/admin", data: { "token": "123" } }
  2. Server > { type: CONNECT, namespace: "/admin", data: { sid: "iLnRaVGHY4B75TeVAAAB" } }
  • in case the connection is refused
  1. Client > { type: CONNECT, namespace: "/" }
  2. Server > { type: CONNECT_ERROR, namespace: "/", data: { message: "Not authorized" } }

Sending and receiving data

Once the connection to a namespace is established, the client and the server can begin exchanging data:

  1. CLIENT SERVER
  2. ───────────────────────────────────────────────────────►
  3. { type: EVENT, namespace: "/", data: ["foo"] }
  4. ◄───────────────────────────────────────────────────────
  5. { type: EVENT, namespace: "/", data: ["bar"] }

The payload is mandatory and MUST be a non-empty array. If that’s not the case, then the receiver MUST close the connection.

Examples:

  • with the main namespace
  1. Client > { type: EVENT, namespace: "/", data: ["foo"] }
  • with a custom namespace
  1. Server > { type: EVENT, namespace: "/admin", data: ["bar"] }
  • with binary data
  1. Client > { type: BINARY_EVENT, namespace: "/", data: ["baz", <Buffer <01 02 03 04>> ] }

Acknowledgement

The sender MAY include an event ID in order to request an acknowledgement from the receiver:

  1. CLIENT SERVER
  2. ───────────────────────────────────────────────────────►
  3. { type: EVENT, namespace: "/", data: ["foo"], id: 12 }
  4. ◄───────────────────────────────────────────────────────
  5. { type: ACK, namespace: "/", data: ["bar"], id: 12 }

The receiver MUST respond with an ACK packet with the same event ID.

The payload is mandatory and MUST be an array (possibly empty).

Examples:

  • with the main namespace
  1. Client > { type: EVENT, namespace: "/", data: ["foo"], id: 12 }
  2. Server > { type: ACK, namespace: "/", data: [], id: 12 }
  • with a custom namespace
  1. Server > { type: EVENT, namespace: "/admin", data: ["foo"], id: 13 }
  2. Client > { type: ACK, namespace: "/admin", data: ["bar"], id: 13 }
  • with binary data
  1. Client > { type: BINARY_EVENT, namespace: "/", data: ["foo", <buffer <01 02 03 04> ], id: 14 }
  2. Server > { type: ACK, namespace: "/", data: ["bar"], id: 14 }
  3. or
  4. Server > { type: EVENT, namespace: "/", data: ["foo" ], id: 15 }
  5. Client > { type: BINARY_ACK, namespace: "/", data: ["bar", <buffer <01 02 03 04>], id: 15 }

Disconnection from a namespace

At any time, one side can end the connection to a namespace by sending a DISCONNECT packet:

  1. CLIENT SERVER
  2. ───────────────────────────────────────────────────────►
  3. { type: DISCONNECT, namespace: "/" }

No response is expected from the other side. The low-level connection MAY be kept alive if the client is connected to another namespace.

Packet encoding

This section details the encoding used by the default parser which is included in Socket.IO server and client, and whose source can be found here.

The JavaScript server and client implementations also supports custom parsers, which have different tradeoffs and may benefit to certain kind of applications. Please see socket.io-json-parser or socket.io-msgpack-parser for example.

Please also note that each Socket.IO packet is sent as a Engine.IO message packet (more information here), so the encoded result will be prefixed by the character "4" when sent over the wire (in the request/response body with HTTP long-polling, or in the WebSocket frame).

Format

  1. <packet type>[<# of binary attachments>-][<namespace>,][<acknowledgment id>][JSON-stringified payload without binary]
  2. + binary attachments extracted

Note: the namespace is only included if it is different from the main namespace (/)

Examples

Connection to a namespace

  • with the main namespace

Packet

  1. { type: CONNECT, namespace: "/" }

Encoded

  1. 0
  • with a custom namespace

Packet

  1. { type: CONNECT, namespace: "/admin", data: { sid: "oSO0OpakMV_3jnilAAAA" } }

Encoded

  1. 0/admin,{"sid":"oSO0OpakMV_3jnilAAAA"}
  • in case the connection is refused

Packet

  1. { type: CONNECT_ERROR, namespace: "/", data: { message: "Not authorized" } }

Encoded

  1. 4{"message":"Not authorized"}

Sending and receiving data

  • with the main namespace

Packet

  1. { type: EVENT, namespace: "/", data: ["foo"] }

Encoded

  1. 2["foo"]
  • with a custom namespace

Packet

  1. { type: EVENT, namespace: "/admin", data: ["bar"] }

Encoded

  1. 2/admin,["bar"]
  • with binary data

Packet

  1. { type: BINARY_EVENT, namespace: "/", data: ["baz", <Buffer <01 02 03 04>> ] }

Encoded

  1. 51-["baz",{"_placeholder":true,"num":0}]
  2. + <Buffer <01 02 03 04>>
  • with multiple attachments

Packet

  1. { type: BINARY_EVENT, namespace: "/admin", data: ["baz", <Buffer <01 02>>, <Buffer <03 04>> ] }

Encoded

  1. 52-/admin,["baz",{"_placeholder":true,"num":0},{"_placeholder":true,"num":1}]
  2. + <Buffer <01 02>>
  3. + <Buffer <03 04>>

Please remember that each Socket.IO packet is wrapped in a Engine.IO message packet, so they will be prefixed by the character "4" when sent over the wire.

Example: { type: EVENT, namespace: "/", data: ["foo"] } will be sent as 42["foo"]

Acknowledgement

  • with the main namespace

Packet

  1. { type: EVENT, namespace: "/", data: ["foo"], id: 12 }

Encoded

  1. 212["foo"]
  • with a custom namespace

Packet

  1. { type: ACK, namespace: "/admin", data: ["bar"], id: 13 }

Encoded

  1. 3/admin,13["bar"]`
  • with binary data

Packet

  1. { type: BINARY_ACK, namespace: "/", data: ["bar", <Buffer <01 02 03 04>>], id: 15 }

Encoded

  1. 61-15["bar",{"_placeholder":true,"num":0}]
  2. + <Buffer <01 02 03 04>>

Disconnection from a namespace

  • with the main namespace

Packet

  1. { type: DISCONNECT, namespace: "/" }

Encoded

  1. 1
  • with a custom namespace
  1. { type: DISCONNECT, namespace: "/admin" }

Encoded

  1. 1/admin,

Sample session

Here is an example of what is sent over the wire when combining both the Engine.IO and the Socket.IO protocols.

  • Request n°1 (open packet)
  1. GET /socket.io/?EIO=4&transport=polling&t=N8hyd6w
  2. < HTTP/1.1 200 OK
  3. < Content-Type: text/plain; charset=UTF-8
  4. 0{"sid":"lv_VI97HAXpY6yYWAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000,"maxPayload":1000000}

Details:

  1. 0 => Engine.IO "open" packet type
  2. {"sid":... => the Engine.IO handshake data

Note: the t query param is used to ensure that the request is not cached by the browser.

  • Request n°2 (namespace connection request):
  1. POST /socket.io/?EIO=4&transport=polling&t=N8hyd7H&sid=lv_VI97HAXpY6yYWAAAC
  2. < HTTP/1.1 200 OK
  3. < Content-Type: text/plain; charset=UTF-8
  4. 40

Details:

  1. 4 => Engine.IO "message" packet type
  2. 0 => Socket.IO "CONNECT" packet type
  • Request n°3 (namespace connection approval)
  1. GET /socket.io/?EIO=4&transport=polling&t=N8hyd7H&sid=lv_VI97HAXpY6yYWAAAC
  2. < HTTP/1.1 200 OK
  3. < Content-Type: text/plain; charset=UTF-8
  4. 40{"sid":"wZX3oN0bSVIhsaknAAAI"}
  • Request n°4

socket.emit('hey', 'Jude') is executed on the server:

  1. GET /socket.io/?EIO=4&transport=polling&t=N8hyd7H&sid=lv_VI97HAXpY6yYWAAAC
  2. < HTTP/1.1 200 OK
  3. < Content-Type: text/plain; charset=UTF-8
  4. 42["hey","Jude"]

Details:

  1. 4 => Engine.IO "message" packet type
  2. 2 => Socket.IO "EVENT" packet type
  3. [...] => content
  • Request n°5 (message out)

socket.emit('hello'); socket.emit('world'); is executed on the client:

  1. POST /socket.io/?EIO=4&transport=polling&t=N8hzxke&sid=lv_VI97HAXpY6yYWAAAC
  2. > Content-Type: text/plain; charset=UTF-8
  3. 42["hello"]\x1e42["world"]
  4. < HTTP/1.1 200 OK
  5. < Content-Type: text/plain; charset=UTF-8
  6. ok

Details:

  1. 4 => Engine.IO "message" packet type
  2. 2 => Socket.IO "EVENT" packet type
  3. ["hello"] => the 1st content
  4. \x1e => separator
  5. 4 => Engine.IO "message" packet type
  6. 2 => Socket.IO "EVENT" packet type
  7. ["world"] => the 2nd content
  • Request n°6 (WebSocket upgrade)
  1. GET /socket.io/?EIO=4&transport=websocket&sid=lv_VI97HAXpY6yYWAAAC
  2. < HTTP/1.1 101 Switching Protocols

WebSocket frames:

  1. < 2probe => Engine.IO probe request
  2. > 3probe => Engine.IO probe response
  3. > 5 => Engine.IO "upgrade" packet type
  4. > 42["hello"]
  5. > 42["world"]
  6. > 40/admin, => request access to the admin namespace (Socket.IO "CONNECT" packet)
  7. < 40/admin,{"sid":"-G5j-67EZFp-q59rADQM"} => grant access to the admin namespace
  8. > 42/admin,1["tellme"] => Socket.IO "EVENT" packet with acknowledgement
  9. < 461-/admin,1[{"_placeholder":true,"num":0}] => Socket.IO "BINARY_ACK" packet with a placeholder
  10. < <binary> => the binary attachment (sent in the following frame)
  11. ... after a while without message
  12. > 2 => Engine.IO "ping" packet type
  13. < 3 => Engine.IO "pong" packet type
  14. > 1 => Engine.IO "close" packet type

History

Difference between v5 and v4

The 5th revision (current) of the Socket.IO protocol is used in Socket.IO v3 and above (v3.0.0 was released in November 2020).

It is built on top of the 4th revision of the Engine.IO protocol (hence the EIO=4 query parameter).

List of changes:

  • remove the implicit connection to the default namespace

In previous versions, a client was always connected to the default namespace, even if it requested access to another namespace.

This is not the case anymore, the client must send a CONNECT packet in any case.

Commits: 09b6f23 (server) and 249e0be (client)

  • rename ERROR to CONNECT_ERROR

The meaning and the code number (4) are not modified: this packet type is still used by the server when the connection to a namespace is refused. But we feel the name is more self-descriptive.

Commits: d16c035 (server) and 13e1db7c (client).

  • the CONNECT packet now can contain a payload

The client can send a payload for authentication/authorization purposes. Example:

  1. {
  2. "type": 0,
  3. "nsp": "/admin",
  4. "data": {
  5. "token": "123"
  6. }
  7. }

In case of success, the server responds with a payload contain the ID of the Socket. Example:

  1. {
  2. "type": 0,
  3. "nsp": "/admin",
  4. "data": {
  5. "sid": "CjdVH4TQvovi1VvgAC5Z"
  6. }
  7. }

This change means that the ID of the Socket.IO connection will now be different from the ID of the underlying Engine.IO connection (the one that is found in the query parameters of the HTTP requests).

Commits: 2875d2c (server) and bbe94ad (client)

  • the payload CONNECT_ERROR packet is now an object instead of a plain string

Commits: 54bf4a4 (server) and 0939395 (client)

Difference between v4 and v3

The 4th revision of the Socket.IO protocol is used in Socket.IO v1 (v1.0.3 was released in June 2014) and v2 (v2.0.0 was released in May 2017).

The details of the revision can be found here: https://github.com/socketio/socket.io-protocol/tree/v4

It is built on top of the 3rd revision of the Engine.IO protocol (hence the EIO=3 query parameter).

List of changes:

  • add a BINARY_ACK packet type

Previously, an ACK packet was always treated as if it may contain binary objects, with recursive search for such objects, which could hurt performance.

Reference: https://github.com/socketio/socket.io-parser/commit/ca4f42a922ba7078e840b1bc09fe3ad618acc065

Difference between v3 and v2

The 3rd revision of the Socket.IO protocol is used in early Socket.IO v1 versions (socket.io@1.0.0...1.0.2) (released in May 2014).

The details of the revision can be found here: https://github.com/socketio/socket.io-protocol/tree/v3

List of changes:

  • remove the usage of msgpack to encode packets containing binary objects (see also 299849b)

Difference between v2 and v1

List of changes:

  • add a BINARY_EVENT packet type

This was added during the work towards Socket.IO 1.0, in order to add support for binary objects. The BINARY_EVENT packets were encoded with msgpack.

Initial revision

This first revision was the result of the split between the Engine.IO protocol (low-level plumbing with WebSocket / HTTP long-polling, heartbeat) and the Socket.IO protocol. It was never included in a Socket.IO release, but paved the way for the next iterations.

Test suite

The test suite in the test-suite/ directory lets you check the compliance of a server implementation.

Usage:

  • in Node.js: npm ci && npm test
  • in a browser: simply open the index.html file in your browser

For reference, here is expected configuration for the JavaScript server to pass all tests:

  1. import { Server } from "socket.io";
  2. const io = new Server(3000, {
  3. pingInterval: 300,
  4. pingTimeout: 200,
  5. maxPayload: 1000000,
  6. cors: {
  7. origin: "*"
  8. }
  9. });
  10. io.on("connection", (socket) => {
  11. socket.emit("auth", socket.handshake.auth);
  12. socket.on("message", (...args) => {
  13. socket.emit.apply(socket, ["message-back", ...args]);
  14. });
  15. socket.on("message-with-ack", (...args) => {
  16. const ack = args.pop();
  17. ack(...args);
  18. })
  19. });
  20. io.of("/custom").on("connection", (socket) => {
  21. socket.emit("auth", socket.handshake.auth);
  22. });