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
相关推荐
IT_陈寒17 分钟前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
Csvn41 分钟前
Nginx 与 OpenResty:阶段钩子、shared dict 与动态 upstream/证书
后端·nginx
geovindu2 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
Java与AI落地2 小时前
RAG 第二步:检索质量不行,先别换模型
后端
JavaGuide2 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
喵个咪2 小时前
RushWind Admin — 模块化单体:一个进程与通往微服务的五级阶梯
后端·架构·rust
用户69371750013843 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
Hespethorn3 小时前
文件该放在哪:十个位置、三处边界、三份声明
后端·架构
喵个咪3 小时前
RushWind CMS — 最小微服务实例:微服务架构的最小完备集
后端·架构·rust
彭亚川Allen3 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试