Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 36 ยท Getting Started

How Socket.IO Works

Understand the two layers under Socket.IO, Engine.IO and the Socket.IO protocol, how the handshake and transport upgrade work, and what event packets look like on the wire.

Socket.IO looks like magic from the outside: you call emit and a function runs on another machine. Under the hood there are two cooperating layers, each with a small, readable protocol. Knowing them makes debugging much easier, because you can read the browser's Network tab and understand every frame you see.

Two layers

Engine.IO is the lower layer. It owns the connection: the handshake, choosing a transport, heartbeats (ping and pong), detecting a dead connection, and closing. It moves opaque "messages" back and forth and does not care what is inside them.

Socket.IO is the upper layer. It owns the meaning: event names, arguments, namespaces, acknowledgement ids, binary attachments, and connect/disconnect per namespace. It encodes each of these as text and hands it to Engine.IO as a message.

flowchart TB
    A["Your code<br/>socket.emit / socket.on"] --> B["Socket.IO<br/>events, namespaces, acks"]
    B --> C["Engine.IO<br/>handshake, heartbeat, upgrade"]
    C --> D["Transport<br/>HTTP long-polling or WebSocket"]

Your event travels down through each layer on the sender and back up on the receiver.

Transports and the upgrade

A transport is the actual pipe. Socket.IO supports two main ones:

  • HTTP long-polling. The client sends GET requests that the server holds open until it has data (or a timeout), and POST requests to upload messages. It works anywhere HTTP works.
  • WebSocket. One persistent, full-duplex connection. Faster and lighter, but some proxies and corporate networks block it.

By default the client opens with long-polling, because it almost always succeeds, then tries to upgrade to WebSocket in the background. If the upgrade works, polling is dropped and the rest of the session uses WebSocket. If it fails, the app keeps working on polling. You can change the order with the transports option; for example transports: ['websocket'] skips polling entirely (read-only snippet):

JavaScript
const socket = io('https://example.com', {
  transports: ['websocket'], // no polling, no upgrade step
});

socket.on('connect', () => {
  console.log(socket.io.engine.transport.name); // "websocket"
});

If you force WebSocket only and you run several server processes behind a load balancer, you avoid the sticky-session requirement of polling for the initial handshake. If you keep polling, every request of one session must reach the same server process. Chapter 5 covers this in detail.

The handshake step by step

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: GET /socket.io/?EIO=4&transport=polling
    S-->>C: 0{"sid":"...","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
    C->>S: POST: 40 (connect to the main namespace)
    S-->>C: 40{"sid":"..."} (namespace connected)
    C->>S: WebSocket handshake (same sid)
    C->>S: 2probe
    S-->>C: 3probe
    C->>S: 5 (upgrade complete)
    S-->>C: 2 (ping)
    C->>S: 3 (pong)

The EIO=4 query parameter is the Engine.IO protocol version.

  1. The first request opens an Engine.IO session. The server answers with an open packet containing a session id (sid), the transports it can upgrade to, and heartbeat settings.
  2. The client asks to join a Socket.IO namespace (the default is /). The server confirms, and now your connection handler runs and socket.id exists on both sides.
  3. The client probes the WebSocket transport with a 2probe / 3probe exchange and then sends the upgrade packet 5.
  4. Every pingInterval (25 seconds by default) the server sends a ping and the client replies with a pong. If no pong arrives within pingTimeout the server closes the connection, which is how a vanished mobile phone is eventually noticed.

Anatomy of a packet

An Engine.IO packet starts with one digit for its type:

Digit Meaning
0 open (handshake data)
1 close
2 ping
3 pong
4 message (carries a Socket.IO packet)
5 upgrade
6 noop

When the Engine.IO type is 4, the rest is a Socket.IO packet, which starts with its own type digit:

Digit Name Example
0 CONNECT 40
1 DISCONNECT 41
2 EVENT 42["hello","world"]
3 ACK 4312["ok"]
4 CONNECT_ERROR 44{"message":"no"}
5 BINARY_EVENT 451-["upload",{"_placeholder":true,"num":0}]
6 BINARY_ACK 461-12[...]

After the type digit may come a namespace (only if it is not /, followed by a comma), an acknowledgement id (digits), and finally a JSON payload. For events the payload is an array: the event name first, then the arguments. So 42/admin,7["ban","u42"] reads: message (4), EVENT (2), namespace /admin, ack id 7, event ban with argument "u42".

The following program is a small encoder and decoder for that format. It is our own implementation for learning, not the library's code, and it runs in plain Node.

Node.js Encoding and decoding Socket.IO packets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that 4212["add",1,2] is ambiguous to a human eye (is 12 part of the type?), but not to the decoder: the type is always exactly one digit after the 4, then digits until the JSON starts at [ or {.

Reading a connection trace

Now read a short trace like the one you would copy from the browser's WebSocket frames panel. The program labels each frame with its Engine.IO meaning and, for messages, the Socket.IO meaning.

Node.js Labelling frames from a trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real browsers show the same strings in DevTools: open the Network tab, filter by WS, pick the socket.io request and look at the Messages list. Arrows up are client frames, arrows down are server frames.

Binary data and payload limits

Text-based JSON cannot hold raw bytes. When an event argument contains a Buffer, ArrayBuffer or typed array, Socket.IO replaces it in the JSON with a placeholder ({"_placeholder":true,"num":0}) and sends the bytes as a separate binary frame right after. The packet type becomes BINARY_EVENT (5) and the number before the dash says how many attachments follow. The receiving side puts the bytes back before your handler runs, so you never see placeholders in application code.

The server also caps the size of a single message (maxHttpBufferSize, 1 MB by default). Larger messages close the connection, so upload big files in chunks or with plain HTTP.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which layer is responsible for heartbeats and choosing the transport?

    Engine.IO owns the connection: handshake, ping/pong, upgrade and close. Socket.IO builds events on top of it.
  2. 2. What does the packet 42["hello","world"] represent?

    4 is an Engine.IO message, 2 is the EVENT type, and the array holds the event name followed by its arguments.
  3. 3. Why does the client usually start with HTTP long-polling and then upgrade?

    Polling works nearly everywhere, so the connection is established quickly and then upgraded when WebSocket is available.
  4. 4. Who sends the periodic ping in Socket.IO v4 and later?

    The server pings every pingInterval and the client answers with a pong; missing pongs close the connection.

Summary

  • Socket.IO sits on top of Engine.IO; Engine.IO manages the connection, Socket.IO manages events.
  • Connections start on HTTP long-polling and upgrade to WebSocket when possible; transports changes that.
  • Packets are short strings: an Engine.IO type digit, a Socket.IO type digit, an optional namespace, an optional ack id and a JSON payload.
  • The server pings, the client pongs; silence closes the connection.
  • Binary values are sent as separate frames and replaced by placeholders in the JSON.

Next: Your First Server and Client