WebSocket实现方式

1.安装组件channels

pip install channels

2.注册app

daphne

python 复制代码
INSTALLED_APPS = [
    'daphne',           #channels4.0以后要引入
    'channels',         # 即时通信
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]
3.在setting中添加ASGI------APPLICATION
复制代码
WSGI_APPLICATION = 'MyBlog.wsgi.application'
ASGI_APPLICATION = 'MyBlog.wsgi.application'
4.在app01中创建consumers.py文件
pyhton 复制代码
from channels.exceptions import StopConsumer
from channels.generic.websocket import WebsocketConsumer


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # 有客户端向后端发送websocket请求时自动触发
        # 服务端允许和客户端创建链接
        self.accept()

    def websocket_receive(self, message):
        # 浏览器基于websocket向后端发送数据,自动触发接受xi消息
        print(message)
        self.send("不要回复!")
    def websocket_disconnect(self, message):
        # 客户端与服务端断开连接时自动触发
        print("断开连接!")
        raise StopConsumer()
5.在setting.py同级目录中创建routing.py文件
python 复制代码
from django.urls import re_path

from app01 import consumers

websocket_urlpatterns = [
    re_path(r'ws/(?P<group>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
6.修改asgi.py文件
python 复制代码
import os

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

from MyBlog import routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyBlog.settings')

application = ProtocolTypeRouter({
   "http": get_asgi_application(),  # 找urls.py 找视图函数
   "websocket": URLRouter(routing.websocket_urlpatterns)  # 找routing(urls)  consumers(views)
})
相关推荐
fruge2 小时前
ClipSketch AI视频转手绘故事板实战:关键帧选取、Gemini绘图与文案生成
网络·网络协议·http
孤狼GPT6 小时前
ChatGPT、Codex工程实战:WebSocket连接正常,为什么文件上传还是会卡住或失败?
websocket·chatgpt·codex·工程实战·工程排障
蔚蓝忧郁7 小时前
使用 matter-dissector 抓包解析 Matter 协议报文
网络协议
ss2738 小时前
FastAPI WebSocket 入门:双向通信、连接管理与广播实践;一条长连接如何撑起实时应用
websocket·网络协议·fastapi
迎風吹頭髮9 小时前
QT中使用QSqlTableModel快速展示SQLite3数据表(TableView实现)
开发语言·qt·sqlite
Multipath71210 小时前
包粒度智能调度・尾时延精准管控- QMP-UDP 多链路聚合
网络·网络协议·安全·udp·智能路由器
小白菜0011 小时前
python之http模块
网络·网络协议·http
奇牙coding1 天前
Grok 4.20 一直报 HTTP 401 怎么办?换了密钥还没好,可能是请求发错了入口
网络·网络协议·http·ai
用户84913717547161 天前
查交换机 24 口的字节数,我差点被一个「正确」的回包骗了
网络协议
Chenyu_3101 天前
AUTOSAR 与 SOME/IP 入门:车载通信是怎么从 CAN 走到 SOA 的
网络·网络协议·tcp/ip·汽车·autopilot