简体   繁体   English

向所有不工作的套接字发出Socket.io

[英]emit to all sockets not working Socket.io

I'm trying to emit a message to all sockets connected to my server using socket.io. 我正在尝试向使用socket.io连接到服务器的所有套接字发出消息。 So far, the code is as follows: 到目前为止,代码如下:

  if(electionExists) { var connectedClients = io.sockets.adapter.rooms[electionRequested].sockets; for(client in connectedClients) { socket.to(client).emit("isVoteValid", {voteToValidate: voteToValidate}); } } 

I made sure that it enters the if(electionExists) condition. 我确保它进入if(electionExists)条件。 Also, I've printed out the array of connected clients, which looks like this: 另外,我已打印出一系列连接的客户端,如下所示:

{ SdiVoIUuGfFL5AJXAAAA: true, 'wLh-EfkAIrWpjx6nAAAC': true }

and just for the sake of it, I printed each client in the loop, which leads to this: 并且仅出于此目的,我在循环中打印了每个客户端,这导致了:

SdiVoIUuGfFL5AJXAAAA
wLh-EfkAIrWpjx6nAAAC

Therefore, I'm led to believe that the problem is not on getting the proper socket id's. 因此,我被认为是问题不在于获得正确的套接字ID。 However, the emit event doesn't work. 但是,发射事件不起作用。 On the client side I have this: 在客户端,我有这个:

  socket.on("isVoteValid", function(obj) {
    console.log("it enters isVoteValid");
  });

which is really, really simple but the console.log never happens. 这确实非常简单,但console.log从未发生。 I really can't see why it is not working. 我真的不明白为什么它不起作用。 Anyone got an idea? 有人知道吗?

If you wanted to broadcast your message then use following code 如果您想广播您的消息,请使用以下代码

if(electionExists) {
      socket.broadcast.emit("isVoteValid", {voteToValidate: voteToValidate});
}

or you can also use this 或者你也可以使用这个

if(electionExists) {
      io.sockets.emit("isVoteValid", {voteToValidate: voteToValidate});
}

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

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