
Socket.IO Cheatsheet: Essential Server-Side Methods and Events
Socket.IO is a JavaScript library that enables real-time, bidirectional, and event-based communication between web clients and servers. It’s widely used for applications like chat systems, live notifications, and collaborative tools, offering an intuitive API to manage connections, emit events, and organize communication with rooms and namespaces. This cheatsheet provides a concise reference for Socket.IO’s core server-side functionality, covering the io
and socket
objects, rooms, namespaces, and built-in events, making it a handy guide for developers building real-time applications.
io (Server-Level Broadcaster)
The io
object manages all connected clients on the server and enables broadcasting events to them.
Method | Description |
---|---|
io.emit(event, data) |
Sends an event to all connected clients. |
io.to(room).emit() |
Sends an event to all clients in a specific room. |
io.in(room).emit() |
Alias for io.to(room).emit() ; targets a room. |
io.of(namespace) |
Targets a namespace (e.g., /admin , /chat ). |
io.sockets.sockets |
Accesses all connected sockets as a Map. |
io.sockets.adapter.rooms |
Lists all active rooms as Sets of socket IDs. |
io.sockets.adapter.sids |
Maps socket IDs to their joined rooms. |
socket (Per-Connection Object)
The socket
object represents an individual client connection, allowing targeted communication and management.
Method | Description |
---|---|
socket.emit(event, data) |
Sends an event to this specific client. |
socket.broadcast.emit() |
Sends to all clients except this socket. |
socket.to(room).emit() |
Sends to others in a room, excluding this socket. |
socket.join(room) |
Adds this socket to a room. |
socket.leave(room) |
Removes this socket from a room. |
socket.disconnect() |
Forcefully disconnects the socket. |
socket.id |
Unique ID for this socket connection. |
socket.rooms |
Set of all rooms this socket is part of. |
socket.handshake |
Contains connection details (headers, query, auth). |
socket.on(event, callback) |
Listens for custom or built-in events from this client. |
socket.data |
Stores custom data, e.g., user info, for this socket. |