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:
- Every parcel is labelled, for example "order status". The label is the event name.
- There is a delivery receipt, so the sender knows the parcel arrived.
- Parcels handed over while the road is closed get delivered once it opens. This is the queue while the connection is down.
- A parcel can go to one address, or to a whole block at the same time. The block is a room.
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 }
})
socket.emit(name, data)sends an event. The name is free. You do not convert the data yourself: objects, arrays and numbers are turned into JSON automatically, and binary data can be sent too.socket.on(name, fn)listens for events with that name, on both sides.socket.broadcast.emit(...)on the server sends to every client except the sender.io.emit(...)sends to everyone.corsis required here. The board onlocalhost:8000and the server onlocalhost:3000are different origins, and the first Socket.IO connection is an ordinary HTTP request.connect,disconnectandconnect_errorare event names Socket.IO uses itself.socket.emit('connect')throws the error"connect" is a reserved event name.
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
- Automatic reconnecting, with no limit on attempts. The delay, from the
socket.io-client4.8.4 code: it starts at 1,000 ms, doubles, is at most 5,000 ms, and is then randomised by ±50%. So the first attempt comes between 500 and 1,500 ms. - A queue. Each
emitwhile disconnected is kept, then sent in order after reconnecting. Tried: two statuses Eko sent while disconnected reached the server after the reconnect, in the same order. - Heartbeat. The server sends a ping every 25 seconds. If no pong comes within 20 seconds, the connection is taken as dead.
- The reason for a drop is passed to
socket.on('disconnect', (reason) => ...). When the reason istransport close(the network dropped), the client reconnects automatically. When the reason isio server disconnect(the server calledsocket.disconnect()), the client does not reconnect. Callsocket.connect()yourself.
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?
- Pick Socket.IO when you want reconnecting, a queue, receipts and rooms without writing them yourself, and you own both the server and the client. Socket.IO servers also exist for Python, Java, Go and more, not just Node.js.
- Pick plain WebSocket (the
wslibrary, or the platform's own WebSocket) when the client is not Socket.IO, for example IoT devices (devices connected to the internet) or someone else's app. Pick plain WebSocket also when every byte counts, or when the platform only gives you plain WebSockets. The Socket.IO client itself is 47,295 bytes, or 14,851 bytes after compressing with gzip (socket.io.min.js4.8.4).
⚠️ Connections that never happen, and a stale queue
- A plain WebSocket to a Socket.IO server. It does not connect, because the two use different protocols.
- Forgetting
corson the server. The browser blocks the first request, andconnect_errorkeeps firing. - Waiting for a reconnect after the server's
socket.disconnect(). The reason isio server disconnect, and the client does not reconnect by itself. - A stale queue. After a long drop, every held
emitgoes out at the same time. Outdated statuses get sent too, so the server has to be ready for old news. If old news is useless, checksocket.connectedfirst, and do not send while disconnected.socket.volatile.emitis meant to drop what you send while disconnected. But when it was tested with socket.io-client 4.8.4, a volatile emit sent during a drop was still held, then sent after the reconnect.
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.