Socket.IO Basics — Realtime

Socket.IO is a library for the server and the browser, on top of WebSocket (through the Engine.IO protocol). Socket.IO adds named events (emit sends, on…

In the WebSocket Fundamentals lesson you still wrote the reconnecting with backoff and jitter yourself. There is more you would have to write too: delivery receipts (proof that a message was received), messages sent while the network is down, and news that should reach only Mr. Darto's phone. Socket.IO takes care of all of it: automatic reconnecting, a queue while disconnected, delivery receipts and rooms. Socket.IO is a library with a server part and a client part, for sending named events back and forth. An event here is a message that has a name. Socket.IO runs on its own protocol, Engine.IO. Engine.IO uses WebSocket as its road, or HTTP long polling when WebSocket is not available.

If WebSocket is a phone line (connected, but you arrange everything yourself), Socket.IO is a courier service:

Server and client

This is Mrs. Rini's realtime server on port 3000, with the package socket.io 4.8.4. The function in io.on('connection', ...) runs each time a client connects, and socket is the connection to that client:

import { Server } from 'socket.io'

const io = new Server(3000, { cors: { origin: 'http://localhost:8000' } })

io.on('connection', (socket) => {
  console.log('connected', socket.id)
  socket.on('order:status', (data, ack) => {
    // save it to the database here
    socket.broadcast.emit('order:status', data) // to every other screen
    ack({ ok: true })                           // a receipt to the sender
  })
})

In the browser, the board and Eko's tablet use the package socket.io-client 4.8.4:

import { io } from 'socket.io-client'

const socket = io('http://localhost:3000')

socket.on('connect', () => console.log('connected', socket.id))
socket.on('order:status', ({ id, status }) => {
  document.querySelector(`#status-${id}`).textContent = status
})
socket.emit('order:status', { id: 12, status: 'Ironing' }, (reply) => {
  console.log(reply) // { ok: true }
})

Over the connection: Engine.IO and Socket.IO packets

Before you look at the recording, guess: Eko's tablet runs socket.emit('order:status', { id: 12, status: 'Ironing' }). Does just the JSON {"id":12,"status":"Ironing"} travel over its WebSocket connection, or something more?

This is a connection recorded from socket.io 4.8.4 (Engine.IO protocol version 4, Socket.IO protocol version 5). -> means the client sent it, and <- means the server sent it:

GET /socket.io/?EIO=4&transport=polling
<- 0{"sid":"...","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000,"maxPayload":1000000}
-> 40                                    <- 40{"sid":"..."}
-> 2probe   <- 3probe   -> 5             (switching to WebSocket)
-> 42["order:status",{"id":12,"status":"Ironing"}]
-> 420["order:status",{"id":13,"status":"Ready for pickup"}]
<- 430[{"ok":true}]
<- 2   -> 3                              (ping from the server, pong from the client)
Digit Layer Meaning
first Engine.IO 0 open, 1 close, 2 ping, 3 pong, 4 message, 5 upgrade, 6 noop
second (when the first is 4) Socket.IO 0 CONNECT, 1 DISCONNECT, 2 EVENT, 3 ACK, 4 CONNECT_ERROR, 5 BINARY_EVENT, 6 BINARY_ACK
after that Socket.IO the receipt number (if any), then a JSON array [event name, data...]

So 42["order:status",{...}] means: a message (4), an event (2), then the name and the data. What travels is not plain JSON but a packet with a number prefix. As a result Socket.IO is not plain WebSocket. new WebSocket('ws://localhost:3000') cannot talk to a Socket.IO server (tried: the connection is refused), and io() cannot connect to a plain WebSocket server.

The client starts over HTTP long polling (transport=polling). Then it tries WebSocket: the client sends 2probe (a test ping), the server answers 3probe, and the client sends 5 (upgrade, the move to WebSocket). Use io(url, { transports: ['websocket'] }) to connect with WebSocket right away.

Receipts: acknowledgements

A function as the last argument of emit is the receipt, called an acknowledgement. That function runs when the server calls ack(...), as in the server code above. Socket.IO gives that event's packet a number, starting at 0 for each socket: 420 means an event with receipt number 0. The server answers with the same number: 430[{"ok":true}]. To set a time limit on the wait, use socket.timeout(...). To wait for the receipt with await, use emitWithAck, which returns a Promise:

socket.timeout(5000).emit('order:status', { id: 13, status: 'Ready for pickup' }, (err, reply) => {
  if (err) console.log('the server did not answer within 5 seconds')
  else console.log(reply) // { ok: true }
})

const reply = await socket.emitWithAck('order:status', { id: 14, status: 'Ready for pickup' }) // the Promise version, since 4.6

When the connection drops: reconnecting and the queue

Rooms, briefly

The server can group sockets (client connections) into rooms. The server puts the connection of Mr. Darto's phone in the room order:12, so the "Ready for pickup" news reaches only that phone:

socket.join('order:12')                                           // on the server
io.to('order:12').emit('order:status', { id: 12, status: 'Ready for pickup' })

Rooms exist only on the server: a client cannot join a room by itself. The details are in the Rooms & Namespaces lesson.

Socket.IO or plain WebSocket?

⚠️ Connections that never happen, and a stale queue

TL;DR: Socket.IO is a library for the server and the browser, on top of WebSocket (through the Engine.IO protocol). Socket.IO adds named events (emit sends, on listens), receipts (acknowledgements) and automatic reconnecting (1 second doubling up to 5 seconds, randomised ±50%). It also adds a queue of emits while disconnected, a fallback (a backup road) to HTTP long polling, rooms (groups of receivers) and namespaces (covered in the Rooms & Namespaces lesson). Over the connection, every packet has a number prefix: 0 open, 2 ping, 3 pong, 40 connect, 42[...] an event, 420[...] an event with receipt number 0, answered by 430[...]. That is why plain WebSocket and Socket.IO cannot connect to each other. Use socket.timeout(ms).emit(...) for a receipt with a time limit, or emitWithAck to wait for it with await, and set cors on the server for the board's origin.

⚡ A named event, with a receipt

Write:

socket.emit('order:status', { id: 12, status: 'Ironing' }, (reply) => {
  console.log(reply) // { ok: true }
})

Meaning: Socket.IO is a library for sending events (messages that have a name) between the browser and the server, and socket is the connection. socket.emit(name, data) sends the event order:status, and the data is turned into JSON automatically. The function as the last argument is the receipt: it runs when the server answers through ack({ ok: true }).

⚡ Over the connection, packets have a prefix

Guess first: Socket.IO runs on top of WebSocket. Eko, who works at the laundry, runs socket.emit('order:status', ...) on his tablet. Does just the JSON data travel over the tablet's WebSocket connection, or something more?

There is a prefix: 42["order:status",{"id":12,"status":"Ironing"}], that is a message (4) and an event (2), then the name and the data.

Meaning: Because of that prefix, Socket.IO is not plain WebSocket. new WebSocket(...) cannot talk to a Socket.IO server, and io(), which opens a Socket.IO connection, cannot connect to a plain WebSocket server.

⚡ When it drops: reconnecting and the queue

Meaning: When the connection drops, Socket.IO reconnects by itself: the delay starts at 1 second, doubles up to 5 seconds, and is then randomised by ±50%. Each emit made while disconnected is kept, then sent in order after reconnecting. But when the server itself cut the connection (the reason io server disconnect), the client does not reconnect: call socket.connect() yourself.

What you will learn