2016-08-24 51 views
0

我目前的工作中,我發送一些參數envents簡單socketio應用程序中獲得的屬性,我將它們存儲到每個插座。Socketio 1.0從所有客戶

socket.on('add user', function (data) { 
    if (addedUser) return; 

    // we store the username in the socket session for this client. 
    socket.nickname = data.nickname; 
    socket.userId = data.userId; 
... 

然後我得到全部採用VAR io.engine.clients socketio客戶和我試圖獲得在其他事件參數是這樣的:

socket.on('new message', function (data) { 

var clientsRoom = io.engine.clients; 

for(var c in clientsRoom){ 
    console.log(" Client: " + c.userId); //Error 
    console.log(" Client: " + c); //outputs the socket ID 
    console.log(" Client: " + c['userId']); //Error 
    } 
... 

,但我無法得到我的用戶ID以前存儲爲所有套接字。我究竟做錯了什麼?

謝謝。

回答

2

而不是io.engine.clients,您應該使用io.sockets.sockets(它們不相同,socket.ioengine.io頂部添加了一個額外的層)。另外,還要確保你把它作爲一個對象,而不是一個數組:

var clientsRoom = io.sockets.sockets; 

for (var id in clientsRoom) { 
    var c = clientsRoom[id]; 
    console.log(" Client: " + c.userId); 
    console.log(" Client: " + id); 
} 
+0

如果我把我的代碼一個日誌後socket.userId = data.userId;打印socket.userId它打印我的用戶ID。但隨着你的代碼,試圖得到它時,將返回我:客戶:未定義:-( – walolinux

+0

@walolinux我把我的要點與測試代碼:https://gist.github.com/robertklep/080f62fc6d7a506d8f5a55bc3bf61252 – robertklep

+0

沒錯,是工作,但我意識到我需要列出所有連接的插座在一個房間裏,不是一般的,然後獲得用戶id ... – walolinux