Node.js Socket.IO

πŸš€ Node.js Socket.IO

Socket.IO is a popular JavaScript library that enables real-time, event-based communication between the browser and the server.

It works on top of WebSockets, but also supports fallback technologies, ensuring reliable realtime communication.


βœ… Why Use Socket.IO?

  • Real-time chat apps

  • Live notifications

  • Real-time dashboards

  • Multiplayer games

  • Live location tracking

  • Collaborative tools (Google Docs–like)


πŸ“¦ 1. Install Socket.IO

Install on Server

npm install socket.io

Install on Client

Include via CDN:

<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>

Or via npm:

npm install socket.io-client

πŸ–₯️ 2. Basic Socket.IO Server (Node.js)

// server.js
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on(“connection”, (socket) => {
console.log(“A user connected:”, socket.id);

socket.on(“disconnect”, () => {
console.log(“User disconnected:”, socket.id);
});
});

server.listen(3000, () => {
console.log(“Server running on port 3000”);
});


🌐 3. Socket.IO Client (Frontend)

<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script>
const socket = io("http://localhost:3000");
socket.on(“connect”, () => {
console.log(“Connected to server:”, socket.id);
});
</script>


πŸ’¬ 4. Sending & Receiving Messages

Server β†’ Client

io.emit("welcome", "Hello from server");

Client

socket.on("welcome", (msg) => {
console.log(msg);
});

Client β†’ Server

socket.emit("chatMessage", "Hi Server");

Server

socket.on("chatMessage", (msg) => {
console.log("Message from client:", msg);
});

πŸ”„ 5. Broadcasting

Send message to everyone except sender:

socket.broadcast.emit("announcement", "A new user joined!");

Send to all clients:

io.emit("announcement", "Server broadcast message");

πŸ‘₯ 6. Rooms (Groups)

Join a Room

socket.join("room1");

Send Message to a Room

io.to("room1").emit("roomMessage", "Hello Room 1");

πŸ§ͺ 7. Simple Chat App (Full Example)

server.js

const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on(“connection”, (socket) => {
console.log(“User Connected:”, socket.id);

socket.on(“chat”, (msg) => {
io.emit(“chat”, msg); // send to all
});
});

server.listen(3000, () => {
console.log(“Server running on 3000”);
});

index.html

<!DOCTYPE html>
<html>
<head><title>Chat</title></head>
<body>
<input id=“msg” autocomplete=“off” />
<button onclick=“sendMsg()”>Send</button>

<ul id=“messages”></ul>

<script src=“https://cdn.socket.io/4.0.0/socket.io.min.js”></script>
<script>
const socket = io(“http://localhost:3000”);

function sendMsg() {
const msg = document.getElementById(“msg”).value;
socket.emit(“chat”, msg);
}

socket.on(“chat”, (msg) => {
const li = document.createElement(“li”);
li.textContent = msg;
document.getElementById(“messages”).appendChild(li);
});
</script>

</body>
</html>


πŸ“‘ 8. Socket.IO with Express

Socket.IO works perfectly with Express.

const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);

⚑ 9. Socket.IO with Authentication

io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (token === "12345") {
next();
} else {
next(new Error("Unauthorized"));
}
});

Client:

const socket = io("http://localhost:3000", {
auth: {
token: "12345"
}
});

🏁 Conclusion

Socket.IO makes it SUPER easy to build:

βœ” Real-time apps
βœ” Event-driven interactions
βœ” Live notifications
βœ” Chat systems
βœ” Multiplayer games

You may also like...