Socket.io return 值

Socket.io return value

我有server.js

io.sockets.on('connection', function(socket){
     socket.on('duplicite', function(name){
      for(var i=0; i<clients.length; i++) {
        if(clients[i] == name){
          io.to(socket.id).emit('duplicite', true);
        }else{
          io.to(socket.id).emit('duplicite', false);
        }
      }
    });
});

和client.html

   socket.emit('duplicite', name);
   socket.on('duplicite', function(ret){
    if(ret){
     alert("non-OK");
    }else
    {alert("OK");}
   });

我想找两面派。当第一个套接字与名称 "name" 连接时,一切正常,我收到 "OK" 的警报。但是当第二个套接字与名称 "name" 连接时,我也会收到 "non-OK" 和 "OK" 的警报。

尝试改用对象,使用方括号符号更容易检查现有名称:

/* 
   could use {} but we'll use Object.create(null) to create a basic
   dictionary object, so we don't have to use hasOwnProperty()
*/
var clients = Object.create(null);

io.sockets.on('connection', function(socket){
     socket.on('duplicite', function(name){
        if (!clients[name]) {
            socket.emit('duplicite', false);
            clients[name] = null; // no duplicate so put name onto object
        }
        else socket.emit('duplicite', true);
    });
});

关于您使用数组的原始代码,您应该在第一个 if 条件中放置一个 break;,这样它就不会继续发送消息。