Until now, I’ve mostly worked with RESTful APIs where requests and responses follow a one-way flow (using HTTP). Basically, the client asks for something → the server replies → and that’s it.
But this time around, I had to bring in Socket.IO. And I quickly asked myself: how different is this from HTTP?
Well, HTTP is just request and response. The client makes a call, and the server gives a fixed reply. If you want new updates, you have to ask again and again.
With Socket.IO, it feels different — it gives you live updates without you always needing to call the server.
🌐 A Simple Analogy
Think of HTTP as writing letters ✉️.
You send one, wait for a reply, then send another.
Now, think of WebSocket/Socket.IO as a phone call 📞.
Once connected, both sides can talk freely without hanging up each time.
That simple picture helped me understand it better.
👩💻 How I Set It Up
So this is how I set it up the first time I tried Socket.IO 👇
1. On the Node.js backend:
Normally, I’d just do:
app.listen(port, () => {
console.log(`Server listening on $PORT`);
});
But this time, since I wanted to add Socket.IO, I had to wrap my app with an HTTP server and then use server.listen
instead. I also set it up to send live updates (in this case, “new posts”) to the client:
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
const app = express();
const server = createServer(app);
const io = new Server(server, { cors: { origin: "*" } });
io.on("connection", (socket) => {
console.log("Client connected");
// Send a "new post" update every 5 seconds
setInterval(() => {
socket.emit("newPost", {
title: "📢 New update just arrived!",
content: "This is a live post pushed from the server",
});
}, 5000);
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
server.listen(port, () => {
console.log(`Server listening on $PORT`);
});
2. On the React client:
Then, I went to the client side and connected it like this:
import io from "socket.io-client";
const socket = io("http://localhost:6002");
// Listen for live post updates
socket.on("newPost", (data) => {
console.log("Live update:", data.title, "-", data.content);
});
✨ Wrapping Up
So that’s how I first set it up — changing my app.listen
to server.listen
, and then configuring both sides so the server could push live updates straight to the client.
This was my very first introduction to Socket.IO, and it already made sense how powerful it can be for things like:
- Live chat
- Notifications
- Collaborative apps
I know there’s still much more to learn, but this was a great starting point. If you’ve worked with Socket.IO before and have tips or resources, I’d love to hear them 😁
Top comments (0)