Websocket 未接收来自 Django Channels 服务器的消息

Websocket not receiving messages from Django Channels server

提问人:freak 提问时间:11/17/2023 最后编辑:Temifreak 更新时间:11/17/2023 访问量:40

问:

我目前正在做一个利用 Django Channels 进行 WebSocket 通信的项目。成功建立 WebSocket 连接时,我遇到了客户端未收到消息的问题。

总结:

  • WebSocket 连接建立时没有错误。
  • Django 频道服务器正在发送消息,已验证。
  • 但是,客户端 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}")

routing.py:

from django.urls import re_path
from .consumers import DepartmentCreatedConsumer

websocket_urlpatterns = [
    re_path(r'ws/department_creation/$', DepartmentCreatedConsumer.as_asgi()),
]

服务器配置:

  • 华尔街日报:waitress-serve --listen=*:8000 transposys_main.wsgi:application
  • 合成工业数据:daphne -b 0.0.0.0 -p 8001 transposys_main.asgi:application

其他信息:

  • 尽管连接成功,但 HTML 页面或控制台中未收到任何消息。
python django websocket django-channels

评论


答: 暂无答案