2016-03-07 121 views
0

我正在使用v0.10.37。我的邏輯是全部由我的檢測代碼設置是不正確的。Nodejs檢查客戶端是否仍然連接

如果(typeof運算(socket.to(鍵).connected [關鍵])=== '未定義')

是我目前使用來檢測一下,我也試過的typeof(socket.to(鍵).connected [鍵] .connected它拋出了一個未定義的錯誤(爲什麼我改變了上面的代碼)我需要的代碼工作,所以客戶端數組添加一個新的clientid客戶端時,它會刪除所有無效clientids通知可以順利推送到客戶端。

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

我固定它自己,這個問題被刪除了錯誤的指標。

刪除客戶端[userid [0]] [key]

訣竅。

相關問題