如何正确取消订阅 socket.io 房间并销毁它? [英] How to correctly unsubscribe from a socket.io room and destroy it?

查看:143
本文介绍了如何正确取消订阅 socket.io 房间并销毁它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为每个套接字都有一个内部循环:

I have an internal loop for each socket:

if (!chat.room.list[hash]) { // room has expired
    socket.leave(hash);
    delete chat.user.list[socket.store.data.id].rooms[hash];
    delete socket.store.data.inRooms[hash]; // delete room hash from user store
}

socket.leave(hash) 什么都不做——socket 仍然接收发送到 hash 房间的消息.

socket.leave(hash) does nothing - socket still receives messages sent to hash room.

附带说明 - 如果我与客户端 Anna 和客户端 Bob 连接 - 两者都会收到消息,但如果我与客户端 Bob 重新连接 - Bob 无法向 Anna 发送消息.

As a side note - if I connect with client Anna and client Bob - both receive messages, but if I reconnect with client Bob - Bob cannot send messages to Anna.

是否有完整的 socket io API 文档(因为我找不到 socket.leave(room) 示例)?

Is there somewhere a full socket io API documentation (as I couldn't find socket.leave(room) examples)?

知道了!Socket IO 用斜线保存房间句柄,所以必须使用socket.leave('/'+hash)

Got it! Socket IO saves room handles with slash, so you have to use socket.leave('/'+hash)

推荐答案

socket.io 中的房间是隐式创建和隐式删除的.基本上它们在为空时会自动删除.

Rooms in socket.io are implicitly created and implicitly deleted. Basically they are automatically removed when they are empty.

是的,前面的 / 已在内部添加到房间名称中,但您不需要添加它以从房间中删除插座.

And yes, a preceding / is added to the rooms name internally but you do not need to add this to remove a socket from a room.

尝试在创建房间时触发 console.log(io.sockets.manager.rooms) 以查看内部发生的情况.

Try firing console.log(io.sockets.manager.rooms) whenever a room is created to have a look at what's happening internally.

这篇关于如何正确取消订阅 socket.io 房间并销毁它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆