[英]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);
});
});
关于使用数组的原始代码,应该break;
在您的第一个if条件中,因此它不会一直发送消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.