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
相关推荐
qq_4042658321 分钟前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
J2虾虾21 分钟前
SpringBoot 中给 @Autowired 搭配 @Lazy
java·spring boot·后端
qq_4523962329 分钟前
【Python × AI】Prompt Engineering 深度工程化:打造大模型的“确定性”控制链路
人工智能·python·ai·prompt
Bright Data30 分钟前
Pinterest 数据集示例
后端·python·flask
小江的记录本35 分钟前
【HTTP】HTTP请求方法与状态码(全体系知识总结+附表格)
前端·网络·后端·网络协议·http·状态模式·web
威联通网络存储1 小时前
某新能源汽车研发中心:基于威联通的全闪存数据治理实践
python·汽车
清空mega1 小时前
第4章:JSP 程序设计实战——for、if、动态表格与 99 乘法表
开发语言·python
阿钱真强道1 小时前
06 Python 数据分析入门:集中趋势与离散程度
python·数据挖掘·数据分析·pandas·可视化·python入门·统计学