Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
Socket.io emit from server is not being received by client

I've been experimenting with sockets lately, and I've ran into a bug that I'm not sure why is happening.

I created an index page with a button titled createRoom, which attempts creates a lobby/room in which other users can connect.

//index.js

createBtn.addEventListener('click', () => {
  socket.emit("create-room", socket.id)
})

socket.on("redirect-host", roomId=>{
  console.log("I JUST CREATED: " + roomId);
  window.location.replace("/master") //lobby
})
//server.js

io.on("connection", socket => {
  console.log("a user connected");

  socket.on("create-room", hostId => { //receives the id of the person creating lobby
    let roomId = Math.round(Math.random() * (999999 - 100000) + 100000);
    socket.join(roomId)//generates room and then sends emit back to redirect host
    console.log("Socket " + hostId + " created room: " + roomId);
    socket.to(hostId).emit('redirect-host', roomId);
  })
})

In index, there is a button you can click to generate a room which emits a create-room to server, which then creates a room and emits the room number back and tells server.js to redirect to a lobby screen (/master).

However, nothing seems to happen upon button press. My main suspect is that "redirect-host" is being sent to the wrong place, but then again I am new to sockets so I can't be sure of it.

Thank you.

EDIT: Resolved! To anyone wondering, the parameter "socket" is the connected socket. According to the socketio documentation, .to sends the emit to everyone but itself

Instead used,

io.in(roomId).emit('redirect-host', roomId);

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Socket stands for the connected socket itself. Looking at the documentation:

  // to all clients in room1 except the sender
  socket.to("room1").emit(/* ... */);

Instead, I believe you want the server to send something to ALL clients in the room. For that, use io.in

io.in(roomId).emit('redirect-host', roomId);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda