Django使用WebSocket

django channels 是django支持websocket的一个模块。

1安装.

|-------------------------|
| pip3 install channels |

2.在settings中添加配置

python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
]

ASGI_APPLICATION = "django_channels_demo.routing.application"

3.创建websocket应用和路由

python 复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from chat import consumers


application = ProtocolTypeRouter({
    'websocket': URLRouter([
        url(r'^chat/$', consumers.ChatConsumer),
    ])
})

4.编写处理websocket逻辑业务

python 复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

class ChatConsumer(WebsocketConsumer):

    def websocket_connect(self, message):
        self.accept()

    def websocket_receive(self, message):
        print('接收到消息', message)
        self.send(text_data='收到了')

    def websocket_disconnect(self, message):
        print('客户端断开连接了')
        raise StopConsumer()

5.启动:

python 复制代码
daphne -b 0.0.0.0 -p xxxx xxxx.asgi:application
相关推荐
mldong14 分钟前
同一个节点,同一个人,办两次:jeeflow 的已办撤回
后端·架构
脚本自动化开发7 小时前
折叠双屏MU156LA:写稿修图游戏体验
后端
脚本自动化开发7 小时前
AI短剧800集讲规矩,观众忘了是AI
后端
qq_158895411118 小时前
AI 音乐生成完成后,音频 URL 为什么会过期?一套可恢复的交付方案
python·api·ai音乐
Csvn10 小时前
安装、升级与目录结构
后端·nginx
皮皮林55110 小时前
万能通用!权限系统就该这么设计
后端
Warson_L10 小时前
高性能架构设计
python·go
databook11 小时前
新数据到手,先跑哪几步检查
python·数据分析
GoAI11 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
czq_268671948712 小时前
Python打卡第46天
开发语言·python