𝗦𝗲𝘁𝘁𝗶𝗻𝗴 𝗨𝗽 𝗦𝗼𝗰𝗸𝗲𝘁.𝗶𝗼
Most web apps use HTTP. The flow follows a simple pattern:
Client sends a request. Server sends a response. The connection closes.
This works for authentication or fetching data. It fails when the server needs to send data without a request.
If a teammate updates a task or a status changes, HTTP makes the browser ask "Is there new data?" repeatedly. This is called polling. It wastes resources.
Socket.io solves this. It creates a persistent connection. The connection stays alive.
Communication becomes two-way: Client ↔ Server
The client sends data. The server sends data. This enables real-time apps.
A common mistake is trying to attach Socket.io directly to Express. Express hides the underlying HTTP server. Socket.io needs direct access to that server.
Do this instead:
- Create the server using your Express app.
- Attach Socket.io to that server.
- Start listening on the port.
Socket.io relies on two methods:
• socket.emit(): Send an event. • socket.on(): Listen for an event.
Rooms make Socket.io efficient. Think of them like walkie-talkie channels. You can group users into specific project rooms.
When a user opens a project, they join a room. When an update happens, you emit the event only to that specific room. This prevents sending data to users who do not need it.
Correct implementation matters. Do not put business logic inside the Socket.io handler. Put it in your route handlers.
The correct flow is:
- User sends a request to a route.
- The server updates the database.
- The database operation succeeds.
- The server emits the Socket.io event.
- The clients update their UI.
Never emit an event before the database confirms the change.
To keep your code clean, store the Socket.io instance on the Express app. Use app.set("io", io). This allows any route to access the instance without messy imports.
Real-time communication means users see updates instantly without refreshing the page.
Source: https://dev.to/chinwuba_jeffrey/setting-up-socketio-a42