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
相关推荐
小趴蔡ha7 分钟前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_8685347814 分钟前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
codeGoogle36 分钟前
自研 IM 还是选择第三方 SDK?企业开发者应该如何权衡?
前端·后端·程序员
数字化转型分享点滴1 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03011 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比1 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
xrandzj2 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_3 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
markinmarkin4 小时前
Spring 中Bean 的作用域有哪些?
java·后端·spring
橙子家4 小时前
使用方法 ToDictionary() 来优化查询时间复杂度:O(N*M) -> O(1*M)【C# 基础】
后端