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
相关推荐
Conan在掘金几秒前
ArkTS 进阶之道(3):为哈禁解构声明?类型一眼可见 vs 推断链断裂
后端
晚安code2 分钟前
干掉成山的 if-else:工厂造、策略选,一文讲透两个模式的配合
后端·设计模式
feng尘3 分钟前
深度解析布隆过滤器(Bloom Filter):原理、优缺点与 1000 万黑名单实战
后端·面试
大陈AI4 分钟前
Docker Compose 前后端部署踩坑实录:3 个坑让我的容器反复 Exit(1)
后端
长大19888 分钟前
MySQL 慢查询排查完整流程
后端
苏三说技术41 分钟前
为什么越来越多人使用FastAPI?
后端
老孙讲技术1 小时前
业主半夜想看楼道监控,物业却说「去机房」?我用设备托管+轻应用,把小区摄像头嵌进了社区小程序
后端·物联网
geovindu1 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
二月龙1 小时前
什么是事务四大特性?用业务案例通俗讲透 ACID
后端
RSTJ_16251 小时前
PYTHON+AI LLM DAY ONE HUNDRED AND EIGHTEEN
python