事件发射不起作用 io.sockets.emit()

Event emmission doesn't work io.sockets.emit()

试图为整个套接字连接和连接到套接字的所有客户端发出事件。 使用过,

io.sockets.emit('toALL',{msg: 'this is demo'});

并在 index.html 中使用以下代码行处理它:

socket.on("toALL",function(){
   // If console is putted here still not able to get any msg or response from emit. 
});

您发送到套接字的对象可用作 .on 回调函数的参数。您可以使用 io.emit 向所有客户端广播。

// server
io.emit("toALL", {msg: "this is demo"});
// client
socket.on("toALL", function (msg) {
  console.log(msg); 
});

我的解决方案来自:https://socket.io/get-started/chat#Integrating-Socket-IO

对于server.js:

io.on('connection', function(socket){
   socket.on('toALL', function(msg){
     io.emit('toALL', msg);
   });
 });

对于Client.html

socket.emit('toALL', 'event');
    socket.on('toALL', function(msg){
      alert(msg);
    });