You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已连接Django Channels服务器,但WebSocket无法接收消息求助

问题排查与解决

核心问题:send方法参数错误

你的VideoConsumer中调用self.send()时未指定关键字参数,导致消息无法正确发送。WebsocketConsumer的send方法要求明确传递text_data或bytes_data参数,直接传入字符串不符合方法签名要求。

修正后的consumers.py

import json
from channels.generic.websocket import WebsocketConsumer

class VideoConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        # 明确指定text_data参数传递JSON字符串
        self.send(text_data=json.dumps({'message': 'you are connected!'}))

额外检查点

  1. 路由配置:确保routing.py正确映射WebSocket路径到你的Consumer:
# routing.py
from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/video/$', consumers.VideoConsumer.as_asgi()),
]
  1. ASGI配置:确认settings.py中指定了ASGI应用入口:
ASGI_APPLICATION = '你的项目名称.asgi.application'

修正后重新启动服务,浏览器控制台应该就能收到"you are connected!"消息了。

内容的提问来源于stack exchange,提问作者gtj520

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:25:23