python - 如何在 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 连接,但我不知道该怎么做。
解决方案
推荐阅读
- php - PUT 请求不会将嵌套集合更新到测试中。在之前执行另一个请求时工作
- django - 如何将 ForeignKey 与 ManyToManyField django 查询集相加
- python-3.x - 执行请求双引号
- wso2 - 在 AM 中将 IS 设置为密钥管理器后无法登录 WSO2 IS 管理控制台
- c# - Automapper 从属性映射到类
- php - 动态学说数据库连接
- arm - 尝试为 Ubuntu 18.04 和 ARM Cortex-A9 交叉编译 C++ 代码时出现“条件分支超出范围”
- java - IllegalArgumentException:在 EntityManager 中创建查询时发生异常:
- android - React Native 报错:.dex 文件中的方法引用数不能超过 64K
- python - 试图做出“是/否”反应确认,但机器人不响应反应