在 Django Channels 中,在连接到 WebSocket 后,您可能想要将客户端连接到特定房间组。要创建房间组并将连接器添加到该组,需要在连接器的.as_asgi()方法中执行几个步骤,其中之一是指定房间组的名称。
例如,如果您正在编写一个聊天应用程序,您可以为每个房间组创建一个名称与房间 ID 相关联。在这种情况下,您可以将房间 ID 存储在 WebSocket URL 的路径参数中,然后在.as_asgi()方法中将其提取。
下面是示例代码:
from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter from django.urls import path
from chat.consumers import ChatConsumer, AsyncChatConsumer
application = ProtocolTypeRouter({ "websocket": URLRouter([ path('ws/int:room_id', ChatConsumer.as_asgi()) ]), "channel": ChannelNameRouter({ "background-tasks": AsyncChatConsumer.as_asgi() }) })
from channels.generic.websocket import AsyncWebsocketConsumer
class AsyncChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() self.room_group_name = f"chat_{self.scope['url_route']['kwargs']['room_id']}"
# 加入房间 group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)