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
相关推荐
小飞悟几秒前
浏览器和服务器是怎么“认出你”的?揭秘 Cookie 认证
后端·node.js
一名用户2 分钟前
unity实现梦日记式传送组件
后端·c#·unity3d
wgyang20166 分钟前
我的第一个LangFlow工作流——复读机
python
hai99long7 分钟前
DTP 模型:分布式事务处理的经典架构模型
后端
魔镜魔镜_谁是世界上最漂亮的小仙女7 分钟前
java-web开发
java·后端·架构
Zhen (Evan) Wang13 分钟前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
我爱一条柴ya17 分钟前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程
雷渊29 分钟前
微服务中为什么要设计不同的服务和不同的数据对象,体现了一个什么样的设计思想?
后端
赶紧去巡山43 分钟前
pyhton基础【23】面向对象进阶四
python
无奈何杨1 小时前
CoolGuard风控中新增移动距离和移动速度指标
前端·后端