首页 > 解决方案 > 如何在 django 中使用 asgi 管理 websocket 连接

问题描述

我的应用程序是这样的

# asgi.py
import os

from django.core.asgi import get_asgi_application
from websocket_app.websocket import websocket_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_app.settings')

django_application = get_asgi_application()


async def application(scope, receive, send):
    if scope['type'] == 'http':
        # Let Django handle HTTP requests
        await django_application(scope, receive, send)
    elif scope['type'] == 'websocket':
        # handle websocket connections here
        await websocket_application(scope, receive, send)
    else:
        raise NotImplementedError(f"Unknown scope type { scope['type'] }")

# websocket.py
async def websocket_application(scope, receive, send):
    while True:
        event = await receive()

        if event['type'] == 'websocket.connect':
            await send({
                "type": "websocket.accept"
            })

        if event['type'] == 'websocket.disconnect':
            break

        if event['type'] == 'websocket.receive':
            try:
                # result = json.loads(event['text'])
                await route(scope, event, send)
            except Exception as e:
                await send({
                    "type": "websocket.send",
                    "text": e.__repr__()
                })

当我收到来自 B 客户端的消息时,我想向 A 客户端发送消息,但我不知道如何找到 websocket 连接并将消息发送给 A 客户端。

我想我应该做一些事情来管理多个 websocket 连接,但我不知道该怎么做。

标签: pythondjangowebsocketasgi

解决方案


推荐阅读