简体   繁体   English

Socket.io返回值

[英]Socket.io return value

I have server.js 我有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);
        }
      }
    });
});

and client.html 和client.html

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

I want to find duplicites. 我想找到杜普利特人。 When first socket connected with name "name" everything is OK, and I get alert with "OK". 当第一个使用名称“ name”的套接字连接时,一切正常,并且我收到“ OK”的警报。 But when second socket connected with name "name" i get alert with "non-OK" and "OK" too. 但是,当第二个套接字以名称“ name”连接时,我也会收到“ non-OK”和“ OK”的警报。

Try using an object instead, it's easier to check for existing names using the square-bracket notation: 尝试使用一个对象,使用方括号符号更容易检查现有名称:

/* 
   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);
    });
});

Regarding your original code using an array, you should put a break; 关于使用数组的原始代码,应该break; in your first if condition, so it doesn't keep sending messages. 在您的第一个if条件中,因此它不会一直发送消息。

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

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