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
相关推荐
移远通信几秒前
Helios SDK开发指南__入门应用代码编写
python
天远Date Lab几秒前
Python实战:基于天远二手车估值API构建企业车队资产数字化管理方案
大数据·人工智能·python
tryCbest几秒前
Python之FastAPI 开发框架(第三篇):高级特性与实战
开发语言·python·fastapi
IT_陈寒1 分钟前
SpringBoot 项目启动慢?这5个优化技巧让你的应用快50%
前端·人工智能·后端
BestOrNothing_20151 分钟前
Ubuntu 22.04 下使用 VS Code 搭建 ROS 2 Humble 集成开发环境
c++·vscode·python·ros2·ubuntu22.04
splage5 分钟前
Spring Framework 中文官方文档
java·后端·spring
ZTLJQ13 分钟前
挖掘金矿:Python数据解析库完全解析
开发语言·python
ONE_SIX_MIX21 分钟前
lancedb 表名 编解码 与 转译 python
开发语言·python
2501_9454248021 分钟前
机器学习与人工智能
jvm·数据库·python
BatyTao22 分钟前
Python从零起步-Python函数
python