useEffect(() => {
const newSocket = io.connect(“production-url”);
setSocket(newSocket);
fetch(production-url/api/room/${classroom}/messages
)
.then(response => response.json())
.then(messages => {
setChat(messages);
})
.catch(error => {
console.error('Error retrieving chat messages:', error);
})
.finally(() => {
setIsLoading(false); // Set isLoading to false when messages are fetched
});
newSocket.emit("joinRoom", classroom);
newSocket.on("chat", (payload) => {
setChat((prevChat) => [...prevChat, payload]);
});
return () => {
newSocket.emit("leaveRoom", classroom);
newSocket.disconnect();
};
}, );
this is the code of client side
const Chat = require(‘./models/Chats’)
const server = require(‘http’).createServer();
const io = require(‘socket.io’)(server, {
cors: {
origin: “localhost-url”
},
});
// Add a room parameter to the connection event
io.on(‘connection’, (socket) => {
console.log(“io function running”)
socket.on(“chat”, (payload) => {
console.log(payload);
io.to(payload.room).emit(“chat”, payload);
const chatMessage = new Chat({
message: payload.message,
username: payload.username,
room: payload.room,
userid: payload.userid,
timestamp: payload.timestamp,
});
chatMessage.save()
.then(() => {
console.log(‘Chat message saved to the database.’);
})
.catch((error) => {
console.error(‘Error saving chat message to the database:’, error);
});
});
socket.on(“joinRoom”, (room) => {
socket.join(room);
console.log(User joined room: ${room}
);
});
socket.on(“leaveRoom”, (room) => {
socket.leave(room);
console.log(User left room: ${room}
);
});
});
const port = 5000;
server.listen(port, () => {
console.log(Socket.io server listening on port ${port}
);
});
module.exports = io;
this is the code of server side
the application works perfectly fine in development but gives the following error when deployed
polling.js:298 GET https://isd-b4ev.onrender.com/socket.io/?EIO=4&transport=polling&t=ObLQ4ZU 404