我正在使用v0.10.37。我的逻辑是由我的检测代码设置不正确的。
if(typeof(socket.to(key).connected [key])==='undefined')
是我目前用来检测的,我也尝试过typeof(socket.to(key).connected [key] .connected,它引发了一个未定义的错误(我将代码更改为上面的原因)。我需要代码工作,以便客户端数组在向客户端添加新的clientid时删除所有无效的clientid,以便通知可以顺利推送到客户端。
var http = require('http');
var io = require('socket.io');
server = http.createServer(function(req, res){});
server.listen(8082);
var socket = io.listen(server);
var clients = {};
socket.on('connection', function(client)
{
client.on('setUserId',function(userid)
{
console.log("add");
if(typeof(clients[userid[0]])==='undefined')
clients[userid[0]] = {};
clients[userid[0]][userid[1]] = userid[1];
console.log(clients);
for(var key in clients[userid[0]])
{
if (typeof(socket.to(key).connected[key]) ==='undefined')
delete clients[userid[0]][userid[1]];
}
});
client.on('removeUserId',function(userid)
{
console.log("remove");
delete clients[userid[0]][userid[1]];
counter = 0;
for(var key in clients[userid[0]])
counter++;
if (counter == 0)
delete clients[userid[0]];
console.log(clients);
});
client.on('message', function(msg)
{
if (msg.indexOf("notifications") != -1)
{
userid = msg.replace("notifications","");
for(var key in clients[userid])
{
sessionid = key;
console.log("notification sent" + msg);
socket.to(sessionid).emit('message',msg);
}
}
else if (msg.indexOf("message") != -1)
{
userid = msg.replace("message","");
for(var key in clients[userid])
{
sessionid = key;
console.log("private message sent" + msg);
socket.to(sessionid).emit('message',msg);
}
}
else
{
ids = msg.split(",");
for (i = 0; i < ids.length;i++)
{
userid = ids[i];
for(var key in clients[userid])
{
sessionid = key;
displaymessage = "notifications" + msg;
console.log("notification sent" + displaymessage);
socket.to(sessionid).emit('message',displaymessage);
}
}
}
})
});
答案 0 :(得分:0)
我自己修复了,问题是删除了错误的索引。
删除客户端[userid [0]] [key]
做了这个伎俩。