简体   繁体   English

Socket.io 客户端未接收到从服务器发出的消息

[英]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.我最近一直在试验 sockets,我遇到了一个错误,我不确定为什么会发生。

I created an index page with a button titled createRoom, which attempts creates a lobby/room in which other users can connect.我创建了一个索引页面,其中包含一个名为 createRoom 的按钮,它尝试创建一个大厅/房间,其他用户可以在其中连接。

//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).在索引中,有一个按钮,您可以单击它来生成一个房间,该按钮向服务器发送一个创建房间,然后服务器创建一个房间并返回房间号,并告诉 server.js 重定向到大厅屏幕 (/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.我的主要怀疑是“redirect-host”被发送到错误的地方,但我又是 sockets 的新手,所以我不能确定。

Thank you.谢谢你。

EDIT: Resolved, To anyone wondering.编辑:已解决,任何想知道的人。 the parameter "socket" is the connected socket, According to the socketio documentation.根据 socketio 文档,参数“socket”是连接的套接字。 .to sends the emit to everyone but itself .to 将 emit 发送给除自身以外的所有人

Instead used,而是使用,

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

Socket stands for the connected socket itself. Socket 代表连接的套接字本身。 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM