Django WebSocket 服务器搭建指南

Django WebSocket 服务器搭建指南

发布时间:2024-10-11 12:55:49

1. 安装必要的包

首先,安装 django channels 和其依赖:

bash
pip install channels daphne

2. 配置 django 项目

settings.py 中添加 channels 配置:

python

installed_apps = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels', # 添加这行
'your_app', # 你的应用名
]

asgi_application = "your_project.asgi.application"

# channels 配置
channel_layers = {
'default': {
'backend': 'channels.layers.inmemorychannellayer'
}
}

3. 创建 asgi 文件

在项目根目录创建或修改 asgi.py

python

import os
from django.core.asgi import get_asgi_application
from channels.routing import protocoltyperouter, urlrouter
from channels.auth import authmiddlewarestack
import your_app.routing # 稍后我们会创建这个

os.environ.setdefault('django_settings_module', 'your_project.settings')

application = protocoltyperouter({
"http": get_asgi_application(),
"websocket": authmiddlewarestack(
urlrouter(
your_app.routing.websocket_urlpatterns
)
),
})

4. 创建 consumer

在你的应用目录中创建 consumers.py

python

from channels.generic.websocket import asyncwebsocketconsumer
import json

class chatconsumer(asyncwebsocketconsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f'chat_{self.room_name}'

# 加入房间组
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)

await self.accept()

async def disconnect(self, close_code):
# 离开房间组
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)

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

# 发送消息到房间组
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)

async def chat_message(self, event):
message = event['message']

# 发送消息到 websocket
await self.send(text_data=json.dumps({
'message': message
}))

5. 配置路由

在你的应用目录中创建 routing.py

python

from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
re_path(r'ws/chat/(?pw+)/$', consumers.chatconsumer.as_asgi()),
]

6. 创建视图和模板

views.py 中:

python

from django.shortcuts import render

def chat_room(request, room_name):
return render(request, 'chat_room.html', {
'room_name': room_name
})

创建 templates/chat_room.html

html




chat room







{{ room_name|json_script:"room-name" }}


7. 配置 url

urls.py 中:

python

from django.urls import path
from . import views

urlpatterns = [
path('chat//', views.chat_room, name='chat_room'),
]

8. 运行服务器

使用 daphne 运行服务器:

bash
daphne your_project.asgi:application

故障排查

  1. websocket 连接失败
    • 检查 url 配置是否正确
    • 确保 asgi_application 设置正确
    • 查看浏览器控制台的错误信息
  2. 消息不广播
    • 检查 channel_layers 配置
    • 确保 group_send 调用正确
  3. 身份验证问题
    • 检查 authmiddlewarestack 配置
    • 确保用户已登录(如果需要)
  4. 性能问题
    • 考虑使用 redis 作为 channel layer 后端
    • 优化消息处理逻辑
  5. 连接突然关闭
    • 检查服务器日志
    • 确保没有未捕获的异常
  6. cors 问题
    • 配置适当的 cors 头
    • 使用 django-cors-headers
  7. ssl/https 配置
    • 确保 websocket url 使用 wss:// 而不是 ws://
    • 正确配置 ssl 证书
  8. 部署问题
    • 确保使用 asgi 服务器(如 daphne 或 uvicorn)
    • 检查反向代理配置(nginx、apache 等)

记住,使用 print() 或日志记录来调试 websocket 代码。你也可以使用 django debug toolbar 的 channels 面板来监控 websocket 连接和消息。

这个指南涵盖了在 django 项目中搭建 websocket 服务器的主要步骤,包括安装必要的包、配置 django 项目、创建 asgi 文件、实现 consumer、配置路由、创建视图和模板,以及运行服务器。我还添加了一些常见问题的故障排查方法。

感谢提供:05互联