已连接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!'}))
额外检查点
- 路由配置:确保
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()), ]
- ASGI配置:确认
settings.py中指定了ASGI应用入口:
ASGI_APPLICATION = '你的项目名称.asgi.application'
修正后重新启动服务,浏览器控制台应该就能收到"you are connected!"消息了。
内容的提问来源于stack exchange,提问作者gtj520
相关产品推荐
相关产品推荐

