Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda