Node.js 事件发射不';t work io.sockets.emit()

Node.js 事件发射不';t work io.sockets.emit(),node.js,sockets,events,socket.io,emit,Node.js,Sockets,Events,Socket.io,Emit,试图为整个套接字连接和连接到该套接字的所有客户端发出事件。 用过, 并在index.html中使用以下代码行处理它: socket.on("toALL",function(){ // If console is putted here still not able to get any msg or response from emit. }); 您发送到套接字的对象可以作为上的回调函数的参数。您可以使用io.emit向所有客户端广播 // server io.emit("toALL"

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

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

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

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

// server
io.emit("toALL", {msg: "this is demo"});

我从以下方面得到了解决方案:

对于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);
    });

在客户端,是否需要使用前缀为http的url调用函数connect()?我在http上运行我的服务器,并在客户端使用,
var socket=io()
,client.html文件。不一定——如果您不提供参数,它假定为相同的域,这可能是您需要的,也可能不是您需要的。如果它无法连接,您应该得到一个错误(您应该与我们分享)。您可以接受自己的答案,这样问题显示为已解决。
io.on('connection', function(socket){
   socket.on('toALL', function(msg){
     io.emit('toALL', msg);
   });
 });
socket.emit('toALL', 'event');
    socket.on('toALL', function(msg){
      alert(msg);
    });