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

Django与Expo集成WebSocket出现404错误的解决问询

Django Channels WebSocket 404 错误排查与解决

问题描述

连接Django后端WebSocket时出现404错误:

Not Found: /ws/
[25/Sep/2023 19:34:58] "GET /ws/ HTTP/1.1" 404 2678

Expo 客户端代码

const socket = React.useRef(new WebSocket('ws://myIP:8000/ws/')).current;
console.log(socket) 
if (socket) {
    // Now you can safely work with the WebSocket object 
} else {
    console.error('WebSocket is undefined.');
}
socket.onmessage = (event) => {
    console.log(event.data)
    // Handle incoming messages from the WebSocket server
};
  
socket.onopen = () => {
    // WebSocket connection opened 
    console.log("opened")
};

socket.onclose = (event) => {
    // WebSocket connection closed
};

socket.onerror = (error) => {
    // Handle WebSocket errors
    console.log("error")
};

Django 后端代码

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
    'channels',
]

ASGI_APPLICATION = 'API.routing.application'

routing.py

from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from .consumers import YourWebSocketConsumer
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "API.settings")

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(
        [
            path("ws/", YourWebSocketConsumer.as_asgi()),
            # Add more WebSocket consumers and paths as needed
        ]
    ),
})

consumers.py

from channels.generic.websocket import AsyncWebsocketConsumer
import json

class YourWebSocketConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        data = json.loads(text_data)
        message = data['message']

        # Process the received message
        # You can send a response back to the client using self.send()

        await self.send(text_data=json.dumps({'message': 'Response to your message'}))

用户疑问:WebSocket是应用核心功能,如何解决该问题?换一台电脑代码就能正常运行,是否需要安装特定组件?


解决步骤

1. 补全依赖安装

换电脑能运行说明代码逻辑无问题,当前环境大概率缺少Channels相关依赖,执行以下命令安装完整组件:

pip install channels channels-redis daphne
  • channels:Django WebSocket核心库
  • channels-redis:Channels的消息路由后端,异步场景必须依赖
  • daphne:官方推荐的ASGI服务器,专门处理WebSocket这类异步请求

2. 修复路由代码漏洞

你的routing.py中缺少os模块导入,会导致ASGI应用初始化失败,需在文件顶部添加:

import os

3. 用ASGI模式启动服务

Django默认runserver可能以WSGI模式启动,无法处理WebSocket请求,必须明确用ASGI模式启动:

  • 方式一:用Django自带命令指定ASGI
python manage.py runserver --asgi
  • 方式二:用daphne直接启动ASGI应用
daphne API.asgi:application

(注意替换API为你的项目根目录名称)

4. 验证网络与访问权限

  • 测试阶段先用ws://localhost:8000/ws/连接,排除公网IP或防火墙拦截问题
  • 确认服务器所在机器的8000端口未被本地防火墙或安全软件阻挡

5. 清理缓存并重启服务

  • 清理Django缓存:python manage.py clearcache
  • 完全关闭当前服务进程后,重新用ASGI模式启动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:51:11