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
相关推荐
夕除5 小时前
js--21
java·python·算法
重生之后端学习5 小时前
994. 腐烂的橘子
java·开发语言·数据结构·后端·算法·深度优先
癫狂的兔子5 小时前
【Python】【机器学习】逻辑回归
python·机器学习·逻辑回归
啊阿狸不会拉杆5 小时前
《计算机视觉:模型、学习和推理》第 2 章-概率概述
人工智能·python·学习·算法·机器学习·计算机视觉·ai
大黄说说6 小时前
Spring Boot 3 新特性详解与迁移指南:从 Java 17 到云原生最佳实践
开发语言·python
尘缘浮梦6 小时前
yield关键字
python
喵手6 小时前
Python爬虫实战:数据质量检测与治理 - 构建健壮的爬虫数据管道(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·零基础python爬虫教学·数据质量检测与治理·爬虫数据管道
honeymoose6 小时前
Webjars 导入到 SpringBoot 项目
后端
何中应6 小时前
虚拟机内的系统无法解析外网域名
linux·运维·后端