簡體   English   中英

Socket.io 將另一個客戶端加入房間

[英]Socket.io join another client to a room

我的目標是當 A 用戶點擊 B 用戶時,他們將加入一個房間。 我為所有客戶端保存了 socket.id 數組。

//CLIENT SIDE FOR A//
$('.chat-start').on('click', function(event) {
        event.preventDefault();
        var room_id = '72xaz132s'
        var target_id = $('.target').data('id');
        socket.emit('force join room', room_id, target_id);
    });

//SERVER SIDE FOR A AS AN EXAMPLE//

var clients {'customIDA' : socket.id for a, 'customIDB' : socket.id for b}

socket.on('force join room', function (roomid, customIDB) { 
        socket.join(chat_id); //CLIENT A JOINS ROOM//
    })

客戶 A 加入房間沒有問題,但我怎樣才能在同一個房間添加客戶 B?

io.on("connection")中,您可以將帶有用戶 ID 的套接字對象存儲為對象

 {"socket": socket, "id": user_id}

排列。 然后從數組中找到索引:

 let user_index = users.findIndex(user => user.id == user_id);

最后加入房間。

 let socketB = users[user_index].socket; socketB.join('room');

您可以調用 join 將套接字訂閱到給定頻道:

// On connection join room
io.on('connection', function(socket){
  socket.join('ROOM ID');
});

然后在廣播或發射時簡單地使用 to 或 in (它們是相同的):

io.to('some room').emit('some event');

要離開頻道,您調用 leave 的方式與加入方式相同。

文檔: https ://socket.io/docs/rooms-and-namespaces/

 function join() { // Run's once clicked console.log('Join function here'); }
 <a href="#" onclick="join()">Join</a>

也許在服務器端處理它? 有一個存儲 User Id 和 Socket Id 的字典,您可以存儲此信息io.on("connection") 然后,當用戶 A 執行創建房間的過程時,將房間 id 和標識用戶 B 的內容發送到服務器端。服務器端計算出用戶 B 的套接字 id 並將它們加入房間。

這種方法有點小技巧,但它確實允許您將任何指定的套接字強制進入完全服務器端的房間,一旦您有了它們的套接字 ID,而無需維護另一個對象數組。 SocketIO (v2.x) 將房間分配存儲在兩個地方以使事情變得有趣。

// $targetSocket is the socket ID of the connection you want to force into a room
    
$roomArray = $io->sockets->connected[$targetSocket]->rooms; //socket's rooms stored here
$roomArray[$newRoom] = $newRoom; // add the new room to this array
$io->sockets->connected[$targetSocket]->rooms = $roomArray; // save the modified array
$io->sockets->adapter->add($targetSocket, $newRoom); // update the adapter too

這顯然是 PHP,但它很容易翻譯成 js。

您也可以反過來將用戶踢出房間:

unset($roomArray[$oldRoom]); //delete room key and value from this socket's array
// save the array here, see above
$io->sockets->adapter->del($targetSocket, $oldRoom); // delete from adapter

一次使用兩者作為休假和加入系統。

當套接字可以使用 socket->join('ROOM') 如此輕松地添加或刪除自己時,這似乎毫無意義; 但在某些情況下,您可能需要從連接的套接字外部執行此操作,例如游戲功能。

對於任何面臨類似問題的人。

@Kouvolan Arnold 的解決方案可以工作,但是必須為每個用戶存儲套接字對象是太多的資源,尤其是當 socket.io 已經存儲了它們時。

一個簡單的解決方案是讓您通過定位它來獲取已經存儲的套接字對象。 好消息是 socket.io 已經提供了,見下文。

//v2.x or less
io.sockets.sockets[USER_SOCKET_ID_HERE]

//v3.x and 4.x
io.sockets.sockets.get(USER_SOCKET_ID_HERE)

下面的代碼在您的情況下效果很好。

//v2.x or less
io.sockets.sockets[clientSocketId].join(roomid);

//v3.x and 4.x
io.sockets.sockets.get(clientSocketId).join(roomid);

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM