简体   繁体   中英

Socket.io return value

I have 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

   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". But when second socket connected with name "name" i get alert with "non-OK" and "OK" too.

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; in your first if condition, so it doesn't keep sending messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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