[英]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.