0% found this document useful (0 votes)
11 views3 pages

Socket File Summary

The document discusses the implementation of a real-time WebSocket server using Socket.io, detailing the code structure for managing user connections and disconnections. It explains how to initialize the socket, authenticate users, and maintain a record of connected users with their respective socket IDs. Additionally, it outlines the utility functions for accessing the Socket.io instance and the connected users map, emphasizing the benefits of tracking online users and enabling direct messaging.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Socket File Summary

The document discusses the implementation of a real-time WebSocket server using Socket.io, detailing the code structure for managing user connections and disconnections. It explains how to initialize the socket, authenticate users, and maintain a record of connected users with their respective socket IDs. Additionally, it outlines the utility functions for accessing the Socket.io instance and the connected users map, emphasizing the benefits of tracking online users and enabling direct messaging.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

8/17/25, 9:26 PM Cupidly project discussion

🔹 Code Explanation
import { Server } from "socket.io"; let io; // will hold socket.io instance

You import Server from socket.io (the class that creates the real-time WebSocket server).
io is declared globally so it can be shared across functions.

const connectedUsers = new Map(); // { userId: socketId }

You’re keeping a record of which user is connected to which socket.


Map is better than plain objects because it handles keys efficiently.
Example:

connectedUsers.set("user123", "socketId_abc")

🔹 Initialize Socket
export const initializeSocket = (httpServer) => { io = new Server(httpServer, { cors: { origin:
"http://localhost:5173", credentials: true, }, });

initializeSocket takes in your HTTP server and attaches socket.io on top of it.
CORS config ensures your frontend (React/Vite running at localhost:5173) can connect to this server.

🔹 Middleware for Authentication


io.use((socket, next) => { const userId = socket.handshake.auth.userId; if (!userId) return
next(new Error("Invalid user ID")); socket.userId = userId; next(); });

socket.handshake.auth contains extra data sent by the client at connection time (frontend
sends userId when connecting).
If no userId → reject the connection.
If valid → attach it to the socket object so you can use it later.
✅ This works similar to Express middleware.

🔹 On New Connection
io.on("connection", (socket) => { console.log(`User connected with socket id: ${socket.id}`);
connectedUsers.set(socket.userId, socket.id);

When a client connects:


You log the connection.
You store userId → socketId mapping in the connectedUsers map.
Example:

https://chatgpt.com/c/68a1f4db-e334-832d-9dbc-fd9f7dd18411 1/3
8/17/25, 9:26 PM Cupidly project discussion

User connected with socket id: abc123


connectedUsers = { "u1": "abc123" }

🔹 Handle Disconnect
socket.on("disconnect", () => { console.log(`User disconnected with socket id: ${socket.id}`);
connectedUsers.delete(socket.userId); }); }); };

When user disconnects (closes tab, internet lost, logs out):


Log it
Remove from connectedUsers map → so you know they’re offline now.

🔹 Export Utility Functions


export const getIO = () => { if (!io) { throw new Error("Socket.io not initialized!"); } return io;
};

Safe way to get your io instance anywhere in your app.

export const getConnectedUsers = () => connectedUsers;

Gives access to the connectedUsers map (so you can check who’s online).

🔹 Real Life Flow (Step by Step)


1. Frontend connects:

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

→ Sends userId to backend.


2. Backend validates:
If userId is missing → reject.
If valid → accept & save in connectedUsers .
3. When user disconnects:
Automatically removed from connectedUsers .

🔹 Why This Is Useful?


✅ You can track who’s online.
✅ Send messages directly to a specific user:

const io = getIO(); const connectedUsers = getConnectedUsers(); const receiverSocketId =


connectedUsers.get("u2"); if (receiverSocketId) { io.to(receiverSocketId).emit("newMessage", {

https://chatgpt.com/c/68a1f4db-e334-832d-9dbc-fd9f7dd18411 2/3
8/17/25, 9:26 PM Cupidly project discussion

from: "u1", text: "Hello!" }); }

https://chatgpt.com/c/68a1f4db-e334-832d-9dbc-fd9f7dd18411 3/3

You might also like