2017-05-07 37 views
0

我已經開始使用socket.io編寫node.js websocket解決方案。Websockets&NodeJS - 更改瀏覽器選項卡和會話

瀏覽器成功連接到節點服務器,我看到了socket.id和與console.log(套接字)關聯的所有配置。我還將一個用戶標識返回給初始連接,並可以在服務器端看到。

問題:我不確定將用戶與連接關聯的最佳方式。我可以看到socket.id每改變一次頁面,打開一個標籤頁都會改變。我如何跟蹤用戶並向所有需要的套接字發送「消息」。 (可能是一個頁面或可能是3個標籤等)。

我試着看看'express-socket.io-session',但我不確定如何爲它編碼和這種情況。

問題:下面有'io'和'app'變量。可以一起使用2嗎? app.use(IO);

本質上我希望能夠跟蹤用戶(我想通過會話 - 但不知道如何處理不同的套接字ID的標籤等),並知道如何回覆用戶或一個或多個套接字。

thankyou

+0

這取決於你如何驗證用戶例如,如果每個套接字都包含具有用戶憑證的標記,則可以通過此標記跟蹤用戶。因此,如果您想向特定用戶發送消息,請搜索您的連接以使用相同的用戶令牌查找這些連接。 –

回答

0

處理這種情況的最好方法是依靠SocketIO的房間。在用戶的唯一ID後命名房間。這將支持開箱即用的多個連接。然後,無論何時您需要與特定用戶進行溝通,只需調用消息函數並傳入他們的ID,事件和任何相關數據即可。您無需擔心明確離開房間,SocketIO會在您的會話超時或關閉瀏覽器選項卡時爲您做這些事情。 (我們明確地離開房間時,他們登出雖然明顯)


在服務器上:

var express = require('express'); 
var socketio = require('socket.io'); 

var app = express(); 
var server = http.createServer(app); 
var io = socketio(server); 

io.on('connect', function (socket) { 
    socket.on('userConnected', socket.join); // Client sends userId 
    socket.on('userDisconnected', socket.leave); // Cliend sends userId 
}); 

// Export this function to be used throughout the server 
function message (userId, event, data) { 
    io.sockets.to(userId).emit(event, data); 
} 

在客戶端:

var socket = io('http://localhost:9000'); // Server endpoint 

socket.on('connect', connectUser); 

socket.on('message', function (data) { 
    console.log(data); 
}); 

// Call whenever a user logs in or is already authenticated 
function connectUser() { 
    var userId = ... // Retrieve userId somehow 
    if (!userId) return; 
    socket.emit('userConnected', userId); 
} 

// Call whenever a user disconnects 
function disconnectUser() { 
    var userId = ... // Retrieve userId somehow 
    if (!userId) return; 
    socket.emit('userDisconnected', userId); 
} 
相關問題