This project uses Socket.IO to enable real-time communication between the server and connected clients. The socket setup is initialized in socket.js
and integrated with the server in app.js
.
To use the socket functionality in a new controller:
-
Import Required Functions:
getIO
: Retrieves the initialized Socket.IO instance.getConnectedUsers
: Provides a mapping of connected users and their respective socket IDs.
import { getIO, getConnectedUsers } from "../config/socket.js";
-
Use Sockets for Real-Time Communication:
Emit events to specific users or broadcast messages
Use getConnectedUsers to find the recipient's socketId
const io = getIO(); // Access the Socket.IO instance const connectedUsers = getConnectedUsers(); // Get connected users const recipientSocketId = connectedUsers[recipientId]; if (recipientSocketId) { io.to(recipientSocketId).emit("eventName", { message: "Your custom message", additionalData: {}, }); }
- Event:
register
- Input:
{ "userId": "<userId>" }
- Output:
User is registered with their socket ID in the connectedUsers object.
- Event:
disconnect
- Input:
None
- Output:
Removes the disconnected user from connectedUsers
- Event:
friendRequestReceived
- Payload:
{ "message": "You have received a new friend request.", "sender": { "id": "<senderId>", "username": "<senderUsername>" } }
- Event:
friendRequestResponded
- Payload:
{ "message": "Your friend request has been <accepted/rejected>.", "recipient": { "id": "<recipientId>", "username": "<recipientUsername>" } }
- Event:
messageReceived
- Payload:
{ "recipient": { "sender": "<senderId>", "content": "<jsonObject>" } }