# Socket.IO and Higher-level Libraries — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-socketio

> Decide when Socket.IO or a managed service is worth it, and explain why a Socket.IO client cannot talk to a plain WebSocket server.

## What Socket.IO adds, and what it costs

**Socket.IO** is a library pair (server and client) that runs its own protocol on top of WebSocket, with HTTP long-polling as a fallback transport. It gives you features you would otherwise build yourself: **automatic reconnection**, **named events** (`socket.emit('chat', data)`), **acknowledgement callbacks**, **rooms** and **namespaces**, and **adapters** (Redis and others) for multi-server broadcasts. The cost is lock-in to its protocol: a Socket.IO client cannot connect to a plain WebSocket server, and a plain `WebSocket` cannot connect to a Socket.IO server, because the messages carry Socket.IO's own packet format. The polling fallback also needs sticky sessions behind a load balancer. Other options include managed services (Ably, Pusher, AWS API Gateway WebSockets, Azure Web PubSub) that hold connections for you, and protocol-level choices such as GraphQL subscriptions or MQTT over WebSockets for IoT. Pick a library when its features match your needs; use raw `ws` when you want a small, standard protocol.

## Rooms and acknowledgements in Socket.IO

`socket.join()` and `socket.to(room).emit()` replace the hand-written rooms map, and the last argument of a handler is an acknowledgement callback.

```js
import { createServer } from 'node:http';
import { Server } from 'socket.io';

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: { origin: 'https://app.example.in' },
});

io.on('connection', (socket) => {
  socket.on('join', (room) => socket.join(room));

  // The client passes a callback; calling it sends an acknowledgement.
  socket.on('chat', ({ room, text }, ack) => {
    socket.to(room).emit('chat', { from: socket.id, text });
    ack({ ok: true });
  });
});

httpServer.listen(3000);
```

## The matching client

The client passes a function as the last argument to `emit`; Socket.IO calls it when the server invokes `ack`. It needs the `socket.io-client` package, not the browser's `WebSocket`.

```js
import { io } from 'socket.io-client';

const socket = io('https://api.example.in');

socket.emit('join', 'cse-2nd-year');
socket.emit('chat', { room: 'cse-2nd-year', text: 'lab at 3?' }, (reply) => {
  console.log('server acknowledged:', reply.ok);
});
socket.on('chat', (msg) => console.log(msg.from, 'says', msg.text));
```

## Interview trap: "Socket.IO is WebSockets"

Socket.IO *uses* WebSocket as a transport, but it is a separate protocol. Saying so precisely, and mentioning the polling fallback and sticky sessions, is a strong interview answer.

**Quiz:** Why does `new WebSocket('wss://api.example.in/socket.io/')` fail to work with a Socket.IO server?

- [ ] Socket.IO servers only accept HTTP/2
- [ ] Browsers block Socket.IO paths
- [ ] Socket.IO requires binary frames only
- [x] Socket.IO uses its own packet protocol and handshake on top of the transport

*Answer:* Socket.IO uses its own packet protocol and handshake on top of the transport. Socket.IO frames its messages in its own format and expects its own connection handshake. Use the official client or a compatible implementation.
