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
相关推荐
parafeeee18 小时前
程序人生-Hello’s P2P
数据库·后端·asp.net
程序媛一枚~18 小时前
✨✨✨使用Python,OpenCV及图片拼接生成❤️LOVE❤️字样图,每张小图加随机颜色边框,大图加随机大小随机颜色边框
图像处理·python·opencv·numpy·图像拼接
MediaTea18 小时前
Python:collections.Counter 常用函数及应用
开发语言·python
如若12318 小时前
flash-attn 安装失败?从报错到成功的完整排雷指南(CUDA 12.8 + PyTorch 2.7)
人工智能·pytorch·python
007张三丰18 小时前
知乎高赞回答爬虫:从零开始,建立你的专属知识库
爬虫·python·知识库·python爬虫·知乎·高赞回答
bug攻城狮19 小时前
Spring Boot应用内存占用分析与优化
java·jvm·spring boot·后端
李昊哲小课19 小时前
Python json模块完整教程
开发语言·python·json
易醒是好梦19 小时前
Python flask demo
开发语言·python·flask
怪侠_岭南一只猿19 小时前
爬虫工程师入门阶段一:基础知识点完全学习文档
css·爬虫·python·学习·html
易龙祥19 小时前
批量下载IGS气象文件(利用python爬虫下载igs的气象数据)
python·igs·气象文件