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
相关推荐
梦想的初衷~7 分钟前
植被遥感反演与数据同化算法体系教程:从PROSAIL前向模拟到作物估产
人工智能·python·机器学习·作物模型·遥感数据同化·prosail·植被参数反演
LadenKiller10 分钟前
近期AI协作写量化规则,要按阶段安排任务
人工智能·python
天天进步201511 分钟前
Python全栈项目--基于深度学习的图像超分辨率系统
开发语言·python·深度学习
济*沧*海18 分钟前
如何判断接口的返回值?
后端
杨充23 分钟前
5.多用组合和少继承
后端
杨充28 分钟前
4.接口而非实现编程
java·后端·架构
ellenwan202643 分钟前
近期AI协作量化实现,先补规则清晰度和流程完整性
人工智能·python
一缕清烟在人间1 小时前
HarmonyOS应用开发实战:萌宠日记 - 生命周期在萌宠日记中的实践
后端
Conan在掘金1 小时前
鸿蒙 ArkUI 组件深水区:Span 富文本嵌套,一行 Text 塞下「红蓝斜下大」五样式 + 动态高亮
后端
卷无止境1 小时前
Python 类型注解与运行时反射:从原理到工程实践
后端·python