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
相关推荐
金銀銅鐵4 分钟前
[Java] 用GUI展示class文件顶层的 access_flags
后端·python·ai编程
kimnoic25 分钟前
Python操作xlwings的实例详解
开发语言·python
2601_9578838429 分钟前
2026年10月 外星人笔记本维修须知
python·电脑
泡茶喝茶写代码37 分钟前
A股量化数据工程:从 REST 接口到策略信号(第 17 篇):创新高与新低扫描
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
IT_陈寒1 小时前
Vue的数组更新把我坑惨了
前端·人工智能·后端
VIP_CQCRE1 小时前
用 Ace Data Cloud 接入 OpenAI 兼容语音转文字:一份能直接运行的 API 指南
python·openai·api·语音识别·acedatacloud
高晶1 小时前
Android 智能语音开发新手入门实战
后端·程序员
励志不掉头发的内向程序员1 小时前
鼠标点一下,图形是怎么画出来的?拆解 CAD 的 Action 状态机
后端·架构
高晶1 小时前
Android 机器视觉新手入门:从扫码到人脸实战
后端·程序员