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
相关推荐
百万蹄蹄向前冲14 小时前
支付宝 VS 微信 小程序差异
前端·后端·微信小程序
一方热衷.20 小时前
YOLO26-Seg ONNXruntime C++/python推理
开发语言·c++·python
YMWM_1 天前
如何将包路径添加到conda环境lerobot的python路径中呢?
人工智能·python·conda
田里的水稻1 天前
ubuntu22.04_openclaw_ROS2
人工智能·python·机器人
凤山老林1 天前
SpringBoot 使用 H2 文本数据库构建轻量级应用
java·数据库·spring boot·后端
梁正雄1 天前
Python前端-2-css练习
前端·css·python
清汤饺子1 天前
用 Cursor 半年了,效率还是没提升?是因为你没用对这 7 个功能
前端·后端·cursor
雨夜之寂1 天前
Browser Use + DeepSeek,我踩了哪些坑
后端·面试
wefly20171 天前
开发者效率神器!jsontop.cn一站式工具集,覆盖开发全流程高频需求
前端·后端·python·django·flask·前端开发工具·后端开发工具
dreamread1 天前
【SpringBoot整合系列】SpringBoot3.x整合Swagger
java·spring boot·后端