提问人:cignestest 提问时间:11/17/2023 最后编辑:cignestest 更新时间:11/20/2023 访问量:25
Websocket 不接收来自 Django 通道服务器 websocket 的消息
Websocket not receiving messages from Django Channels server websocket
问:
我目前正在做一个使用 Django Channels 进行 WebSocket 通信的项目。但是,我遇到了一个问题,即 WebSocket 连接已成功建立,但在客户端未收到消息。
WebSocket 连接已建立,没有错误。
我已经验证了 Django Channels 服务器正在发送消息。
但是,客户端 WebSocket 似乎没有收到任何消息。
我 asgi.py 是
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
import transposys_main.routing
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings')
django.setup()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AllowedHostsOriginValidator(
URLRouter(
transposys_main.routing.websocket_urlpatterns
)
),
})
我 consumer.py 是
import json
from channels.generic.websocket import AsyncWebsocketConsumer
import logging
logger = logging.getLogger(\__name_\_)
logger.setLevel(logging.DEBUG)
class DepartmentCreatedConsumer(AsyncWebsocketConsumer):
async def connect(self):
logger.info(f"WebSocket connected: {self.channel_name}")
await self.accept()
async def disconnect(self, close_code):
logger.info(f"WebSocket disconnected: {self.channel_name}")
async def receive(self, text_data):
logger.info(f"WebSocket message received: {text_data}")
try:
text_data_json = json.loads(text_data)
message_type = text_data_json.get('type')
message = text_data_json.get('message')
if message_type == 'department.created':
logger.info(f"New Department: {message}")
except json.JSONDecodeError as e:
logger.error(f"Error decoding JSON: {e}")
async def department_created(self, event):
try:
logger.info(f"Department created event received: {event\['message'\]}")
await self.send(text_data=json.dumps({
'type': 'department.created',
'message': event\['message'\],
}))
except Exception as e:
logger.error(f"Error sending WebSocket message: {e}")
路由是
from django.urls import re_path
from .consumers import DepartmentCreatedConsumer
websocket_urlpatterns = \[
re_path(r'ws/department_creation/$', DepartmentCreatedConsumer.as_asgi()),
\]
我的 wsgi serve waitress-serve --listen=*:8000 transposys_main.wsgi:application 和 daphne -b 0.0.0.0 -p 8001 中的 asgi transposys_main.asgi:application 我无法收到任何消息
在我的 HTML 浏览器中,我已连接,但是当我发送通知时,该通知在 HTML 页面或控制台中看不到
答: 暂无答案
评论