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
相关推荐
贤哥哥yyds7 分钟前
GBK转UTF\-8编码自动转换工具 使用文档
python
数量技术宅15 分钟前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
华如锦22 分钟前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai
戴西软件41 分钟前
戴西 DLM 许可授权管理系统:破解无网络环境下工业软件授权难题,助力制造企业降本增效
网络·人工智能·python·深度学习·程序人生·算法·制造
Dxy12393102161 小时前
Python线程锁:为什么多线程会“打架“,以及怎么解决
开发语言·前端·python
小白学大数据1 小时前
线上故障急救:依托 OpenClaw 日志排查 403 和 503 问题
爬虫·python·selenium·数据分析
fox_lht1 小时前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
databook2 小时前
用SymPy自动因式分解:从面积拼图到代数恒等式
python·数学·动效
大鸡腿同学2 小时前
用 AI 肝了一个星期的智能客服助手,看看怎么个事
后端