Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io + express rooms

I am working on an online website with real-time chat and I've been trying to set up socket.io rooms for a few days now, but one of my custom events just doesn't emit.

My website has 2 paths, / and /play. When someone fills out a form in the / path, the website redirects them to the /play path.

const io = require('socket.io')(listener);

io.on('connection', socket => {

  socket.on('add user', data => { // This event gets emitted when the user submits the form at `/`, in a client-side js file. 
    socket.username = data.username;
    socket.room = data.room;
    socket.score = 0;
    socket.join(data.room);
    io.sockets.in(data.room).emit('user joined', { // This event gets 'handled', in another (not the same one) client-size js file.
    username: data.username,
    room: data.room
  });
  });

  socket.on('disconnect', function () {
   io.sockets.in(socket.room).emit('user left', {
   username: socket.username,
   room: socket.room
  });
  socket.leave(socket.room)
});


});

In the other client-side js file:

var socket = io.connect();  
let joined = 0;

socket.on('user joined', data => {
  joined++;
  console.log(joined, data)
  const elemental = document.createElement("LI");
  const info = document.createTextNode(data.username);
     elemental.appendChild(info);
   document.getElementById('people').appendChild(info)
});

The add user event code executes just fine, but the user joined one doesn't.. I'm almost certain that it has to do with the paths. I read on socket.io namespaces but it seems like they are just like a different type of rooms. Can someone tell me what's wrong?

EDIT: I should mention that no errors come up.

like image 921
Mxm Avatar asked Jul 11 '26 20:07

Mxm


1 Answers

Without seeing your whole code, I'm going to assume that the socket on client-side.js code, is not joined to the data.room room, and that's why you don't get anything on the 'user join' event listener and that happens because you probably have multiple socket.io connections on the client side code.

You have multiple ways to solve this, depending on what you're trying to achieve.

  • Instead of only emitting to people on the room, emit to all sockets that an user joined a specific room. io.emit('user joined') instead of io.sockets.in(data.room)...
  • There should only be one single var socket = io.connect(); on the front end, otherwise the socket that's emitting: add user and therefore joined to data.room is not the same socket that's listening on: user joined, and that's why you never get the event on that socket, because you have 2 different sockets, one that joined the room, and one that is doing absolutely nothing except waiting for an event that will never occur.
like image 65
Marcos Casagrande Avatar answered Jul 13 '26 10:07

Marcos Casagrande