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
相关推荐
weixin_4074438724 分钟前
OCR材料信息提取工具(附件中含代码和数据)
人工智能·python·计算机视觉·ocr
肌肉娃子28 分钟前
20260603.记一次 Doris FE “幽灵卡死”引发的惨案:从表象到真凶的追凶实录
后端
码农阿强29 分钟前
PixVerse 全系列视频生成模型技术架构详解 + Python 基于 StartAPI.top 接口实战调用
python·ai·架构·音视频·ai编程
Smilecoc38 分钟前
风控评分卡模型原理与应用(四):WOE编码的单调性
python
许彰午42 分钟前
04_Java数组操作全解
java·开发语言·python
学以智用44 分钟前
.NET Core 序列化 **超清晰完整版教程**
后端·.net
废弃的小码农1 小时前
APP测试--adb使用介绍
python·测试工具·adb
Java患者·1 小时前
Spring Boot 3 整合 Elasticsearch 8
spring boot·后端·elasticsearch
雪隐1 小时前
个人电脑玩AI01-让5060 Ti给你打工——Whisper语音识别篇(上)
人工智能·后端
曲幽1 小时前
你的FastAPI又在服务器上“跑不起来”了?来,今天咱把打包这件事彻底聊透
linux·windows·python·docker·fastapi·web·pyinstaller·nssm·services