I am using nodejs
to build a socket connection.
Code –
const socketIO = require('socket.io');
let io;
const usersInRoom = {}; // Object to keep track of users in rooms
const initializeSocket = (server) => {
io = socketIO(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
credentials: true,
},
path: '/new/api/socket.io', // Custom path for WebSocket connections
transports: ['websocket', 'polling'],
});
// io.of('/new/api').on('connection', (socket) => {
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.on('joinRoom', (data) => {
let { groupId, userId } = data;
if (!groupId || !userId) {
return;
}
// Check if the user is already in the room to avoid duplicate join
if (!socket.rooms.has(groupId)) {
socket.join(groupId);
socket.groupId = groupId;
socket.userId = userId;
if (!usersInRoom[groupId]) {
usersInRoom[groupId] = new Set();
}
usersInRoom[groupId].add(userId);
} else {
console.log(`User ${userId} is already in room ${groupId}`);
}
});
socket.on('leaveRoom', () => {
if (usersInRoom[socket.groupId]) {
usersInRoom[socket.groupId].delete(socket.userId);
if (usersInRoom[socket.groupId].size === 0) {
delete usersInRoom[socket.groupId];
}
}
socket.leave(socket.groupId);
});
socket.on('message', (message) => {
// Emit to all users in the room except the sender
socket.broadcast.to(socket.groupId).emit('broadcast-message', message);
});
socket.on('disconnect', () => {
if (usersInRoom[socket.groupId]) {
usersInRoom[socket.groupId].delete(socket.userId);
if (usersInRoom[socket.groupId].size === 0) {
delete usersInRoom[socket.groupId];
}
}
});
});
};
const getIoInstance = () => {
if (!io) {
throw new Error('Socket.io is not initialized!');
}
return io;
};
const getUsersInRoom = (groupId) => {
return usersInRoom[groupId] ? Array.from(usersInRoom[groupId]) : [];
};
module.exports = { initializeSocket, getIoInstance, getUsersInRoom };
My server is running on localhost:5000, when I hot socket connect request on localhost:5000
this get connected with socket and functions working properly, but in production my endpoint is https://example.com/new/api
and when I try to connect socket at this endpoint this did not get connected. This returns 404 error. Host URL is https://example.com/new/api
not https://example.com/
but this is sending request to https://example.com/new/api
. How can I fix this endpoint issue.