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

Django Channels WebSocket连接失败问题求助

Django Channels WebSocket连接失败解决方案

报错信息

WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/example1/' failed:

核心修复步骤

1. 修正ASGI配置

当前asgi.py未加载Channels路由,导致WebSocket请求无法被处理。替换为以下内容:

import os
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

# 初始化Django ASGI应用
django_asgi_app = get_asgi_application()

# 导入项目级Channels路由
from core.routing import application

2. 修复消费者方法错误

consumers.py中disconnect方法使用了不存在的group_discard,替换为正确的group_remove:

async def disconnect(self, close_code):
    await self.channel_layer.group_remove(
        self.room_group_name,
        self.channel_name
    )

3. 统一URL路由语法

应用级routing.py混用旧版url和推荐的re_path,统一为:

from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatRoomConsumer.as_asgi()),
]

4. 使用ASGI兼容服务器

运行项目时需使用支持ASGI的服务器,推荐用daphne:

daphne core.asgi:application

或使用Channels兼容的runserver:

python manage.py runserver

5. 额外检查项

  • 确认channels已添加到settings.py的INSTALLED_APPS中:
    INSTALLED_APPS = [
        # ... 其他应用
        'channels',
    ]
    
  • 若出现403错误,可暂时将AuthMiddlewareStack替换为ChannelsMiddlewareStack测试,排除认证拦截问题。

验证方法

在消费者的connect方法中添加日志,确认连接触发:

async def connect(self):
    self.room_name = self.scope['url_route']['kwargs']['room_name']
    self.room_group_name = 'chat_%s' % self.room_name
    print(f"Connected to room: {self.room_name}")
    await self.channel_layer.group_add(
        self.room_group_name,
        self.channel_name
    )
    await self.accept()

重启服务器后,查看终端日志和浏览器控制台,确认WebSocket连接成功。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:14:53