我知道這個問題很舊,但對於任何人通過谷歌搜索絆倒這一點,這是我如何接近它。
即使沒有加入或離開房間的本地事件,加入房間也很容易計算。
/* client.js */
var socket = io();
socket.on('connect', function() {
// Join a room
socket.emit('joinRoom', "random-room");
});
和服務器端
/* server.js */
// This will have the socket join the room and then broadcast
// to all sockets in the room that someone has joined
socket.on("joinRoom", function (roomName) {
socket.join(roomName);
io.sockets.in(roomName).emit('message','Someone joined the room');
}
// This will have the rooms the current socket is a member of
// the "disconnect" event is after tear-down, so socket.rooms would already be empty
// so we're using disconnecting, which is before tear-down of sockets
socket.on("disconnecting", function() {
var rooms = socket.rooms;
console.log(rooms);
// You can loop through your rooms and emit an action here of leaving
});
它變得有點棘手是當他們斷開,但幸運的是加入一個disconnecting
事件的眼淚在房間插座下來之前,這種情況發生。在上面的例子中,如果事件是disconnect
那麼房間將是空的,但是disconnecting
將具有它們所屬的所有房間。對於我們的示例,您將有兩個房間,插座將成爲其中的一部分,Socket#id
和random-room
我希望這可以指出其他人從我的研究和測試的正確方向。
當你加入/離開時,或當別人做什麼? – cHao
我不確定我明白你在問什麼。我有一個「房間」,我想知道什麼時候_any_套接字加入或離開它。 – lakenen
套接字不加入或離開房間。客戶加入或離開房間。我認爲你對客戶感興趣(那不是你),那麼? – cHao