Getting started with socket.io
By Raju Shrestha • Thu Jan 01 1970

Socket.IO is a JavaScript library that enables real-time, bidirectional communication between clients and servers using WebSockets and fallbacks. It is widely used in: Chat applications, Live notifications, Real-time dashboards, Online multiplayer games, Live streaming systems, Collaborative applications.
1. What is Socket.IO?
Socket.IO provides event-based communication between browser clients and Node.js servers. It automatically chooses the best available transport method. Features: Real-time communication Auto reconnection Broadcasting Rooms and namespaces Binary support Custom events.
2. Installation
Server Installation:
3. Basic Server Setup
4. Basic Client Setup
5. Understanding Events
Socket.IO relies entirely on events to send and receive data. Both sides trigger actions by naming and listening for these events.
Types of Events
- 🔌
connection: Fires on the server when a client connects. - ❌
disconnect: Fires automatically when a user closes the tab. - 💬
message: A default event name built into the system. - 🛠️
custom events: Names you invent yourself to send specific data.
How It Works
6. Sending Messages
The server and client can send messages using emit().
7. Broadcasting
Broadcast sends messages to all connected clients.
8. Rooms
Rooms allow grouping sockets together. Example: chat rooms, game rooms.
9. Namespaces
Namespaces divide application logic. Example: /chat /admin /game
10. Middleware
Middleware runs before socket connection is accepted. Useful for: Authentication Logging Validation
11. Authentication with JWT
Protect Socket.IO connections using JWT.
12. Error Handling
Handle connection and custom errors properly.
13. Socket.IO with React
Using Socket.IO inside React applications.
14. Chat App Example
Build a mini real-time chat application.
15. Conclusion
The conclusion states that Socket.IO is one of the best solutions for real-time communication because it solves the major engineering challenges of persistent, bidirectional web connections out of the box. While raw WebSockets provide the baseline speed, managing them at scale requires writing massive amounts of boilerplate code. Socket.IO abstraction eliminates this operational overhead through several distinct layers.
Important Socket.IO Interview Questions
- What is Socket.IO?
Real-time communication library - What transport does Socket.IO use?
WebSocket + fallbacks - What is emit()?
Used to send events - What is on()?
Used to listen to events - What are rooms?
Groups of sockets - What are namespaces?
Separate communication channels - Why use Redis Adapter?
Scaling multiple servers
Quick Revision Notes: emit() → Send events on() → Listen to events io.emit() → Send to all socket.broadcast.emit() → Send to everyone except sender socket.join() → Join room io.to(room).emit() → Send to room Middleware → Authentication/Validation Namespaces → Separate modules
