Next.js Discord

Discord Forum

Problem with socket.io and nextjs

Answered
Pacific sand lance posted this in #help-forum
Open in Discord
Pacific sand lanceOP
Issue with socket.to in Socket.io Chat App:

I'm working on a real-time chat application using socket.io, and I'm facing an issue with using socket.to to send messages to everyone in a room except the sender. Here are the relevant parts of my code:

Client-side code (React component):

``jsx const room = 'room1'; const handleSubmit = (e) => { e.preventDefault(); const value = 'hello'; socket.emit('send_message', { value, room }); }; const io = require('socket.io')(server); io.on('connection', (socket) => { console.log(User connected: ${socket.id}); socket.on('send_message', (data) => { console.log(data); // The issue is with the following line socket.to(data.room).emit('receive_message', data); }); socket.on('disconnect', () => { console.log(User disconnected: ${socket.id}`);
});
});
The problem is that socket.to(data.room).emit('receive_message', data); doesn't seem to work as expected. I've tried using socket.in as well, but it didn't make a difference. Currently, I'm using socket.broadcast.emit('receive_message', data);, but this sends the message to everyone, including the sender.
Answered by Pacific sand lance
nevermind this is resolved
View full answer

2 Replies

Pacific sand lanceOP
const io = require('socket.io')(server);
io.on('connection', (socket) => {
  console.log(`User connected: ${socket.id}`);

  socket.on('send_message', (data) => {
    console.log(data);
    // The issue is with the following line
    socket.to(data.room).emit('receive_message', data);
  });

  socket.on('disconnect', () => {
    console.log(`User disconnected: ${socket.id}`);
  });
});

https://github.com/ForkEyeee/anonymous-chat-app
Pacific sand lanceOP
nevermind this is resolved
Answer