This cheat sheet provides a comprehensive overview of the Socket.IO library for real-time, bidirectional event-based communication.
Core Concepts
- Events: Communication is based on emitting and listening to named events.
- Bidirectional: Both the client and server can initiate communication.
- Real-time: Low-latency communication, suitable for applications like chat, live stats, and multiplayer games.
1. Server-Side Setup
Installation
npm install socket.io
Basic Server (server.js
)
import { createServer } from "http"; import { Server } from "socket.io"; const httpServer = createServer(); const io = new Server(httpServer, { cors: { origin: "http://localhost:8080", // Allow requests from this origin methods: ["GET", "POST"] } }); io.on("connection", (socket) => { console.log(`Client connected: ${socket.id}`); // Handle disconnection socket.on("disconnect", () => { console.log(`Client disconnected: ${socket.id}`); }); }); httpServer.listen(3000, () => { console.log("Socket.IO server running at http://localhost:3000/"); });
2. Client-Side Setup
Installation
HTML (via CDN)
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
Node.js/Bundler
npm install socket.io-client
Basic Client (index.html
or client.js
)
// For browser const socket = io("http://localhost:3000"); // For Node.js client // import { io } from "socket.io-client"; // const socket = io("http://localhost:3000"); socket.on("connect", () => { console.log(`Connected to server with id: ${socket.id}`); }); socket.on("disconnect", () => { console.log("Disconnected from server"); });
3. Emitting and Listening for Events
Server-Side
io.on("connection", (socket) => { // Listen for a 'messageFromClient' event socket.on("messageFromClient", (data, ack) => { console.log("Message from client:", data); // Acknowledge receipt of the message if (ack) { ack("Server received your message!"); } }); // Emit a 'messageFromServer' event to this specific client socket.emit("messageFromServer", { message: "Welcome to the server!" }); });
Client-Side
// Listen for a 'messageFromServer' event socket.on("messageFromServer", (data) => { console.log("Message from server:", data.message); }); // Emit a 'messageFromClient' event with an acknowledgement socket.emit("messageFromClient", { message: "Hello from the client!" }, (response) => { console.log("Acknowledgement from server:", response); });
4. Broadcasting
Broadcasting sends a message to all connected clients.
// Server-side: Send to all clients io.emit("broadcastMessage", { info: "This is for everyone!" }); // Server-side: Send to all clients *except* the sender socket.broadcast.emit("broadcastMessage", { info: "A new user has joined!" });
5. Rooms
Rooms are channels that sockets can join and leave. They are useful for sending messages to a specific group of clients.
Joining and Leaving a Room
// Server-side io.on("connection", (socket) => { // Join a room socket.join("room1"); // Leave a room socket.leave("room1"); });
Emitting to a Room
// Server-side: Send to all clients in 'room1' io.to("room1").emit("roomMessage", { message: "Hello, room1!" }); // Server-side: Send to all clients in 'room1' except the sender socket.to("room1").emit("roomMessage", { message: "A new user joined room1" });
6. Namespaces
Namespaces are a way to split the logic of your application over a single shared connection.
Server-Side Namespace
// Server-side: Create a namespace const adminNamespace = io.of("/admin"); adminNamespace.on("connection", (socket) => { console.log(`Admin connected: ${socket.id}`); // Middleware for this namespace adminNamespace.use((socket, next) => { // Authentication logic here next(); }); socket.on("adminCommand", (command) => { console.log("Admin command received:", command); }); // Emit to all clients in the admin namespace adminNamespace.emit("adminUpdate", { data: "System is updating..." }); });
Client-Side Namespace
// Client-side: Connect to a namespace const adminSocket = io("http://localhost:3000/admin"); adminSocket.on("connect", () => { console.log("Connected to admin namespace"); }); adminSocket.emit("adminCommand", { command: "restart-server" }); adminSocket.on("adminUpdate", (data) => { console.log("Admin update:", data); });
7. Middleware (Authentication Example)
Middleware can be used to intercept incoming packets. It's commonly used for authentication.
// Server-side: Global middleware io.use((socket, next) => { const token = socket.handshake.auth.token; if (isValid(token)) { return next(); } return next(new Error("authentication error")); }); // Client-side: Sending auth data const socket = io("http://localhost:3000", { auth: { token: "your-jwt-token" } });
8. API Reference
Server-Side (io
or socket
)
Method/Property | Description |
---|---|
io.on('connection', fn) | Listens for new client connections. |
socket.on(event, fn) | Listens for a specific event from a client. |
socket.emit(event, data) | Emits an event to the specific client associated with the socket. |
io.emit(event, data) | Emits an event to all connected clients. |
socket.broadcast.emit(event, data) | Emits to all clients except the sender. |
socket.join(room) | Joins the socket to a specific room. |
socket.leave(room) | Leaves the socket from a room. |
io.to(room).emit(event, data) | Emits an event to all clients in a specific room. |
io.of(namespace) | Creates or retrieves a namespace. |
socket.id | A unique identifier for the socket session. |
socket.rooms | A Set of rooms the socket is currently in. |
io.use(fn) | Registers a middleware function. |
Client-Side (socket
)
Method/Property | Description |
---|---|
io(url, opts) | Creates a new socket connection to the specified URL. |
socket.on(event, fn) | Listens for an event from the server. |
socket.emit(event, data, ack) | Emits an event to the server, with an optional acknowledgement callback. |
socket.id | The unique ID for the client's socket. Changes on each connection. |
socket.connect() | Manually connects the socket. |
socket.disconnect() | Manually disconnects the socket. |
Top comments (0)