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)
})
相关推荐
Lzg_na9 小时前
ARP 地址解析协议详解
网络·网络协议
北京盛世宏博10 小时前
通信异常深度排查:以太网温湿度设备 TCP 粘包、UDP 丢包根治方案
单片机·网络协议·tcp/ip·udp·以太网·传感器·温湿度
paopaokaka_luck11 小时前
滑雪场管理系统(AI智能助手流式对话,ECharts 运营数据分析、教练、雪具与场地一体化预约,钱包支付退款、订单核销与服务评价)
java·人工智能·spring boot·网络协议·数据分析·echarts
CCblandy12 小时前
HTTP 长连接 3 类故障实测:[WinError 10053]、99 个 TIME_WAIT、69 次多余握手,4 种对策怎么选
后端·python·网络协议·http·云原生·性能优化·架构
雪雪爱冲浪13 小时前
2026 年网络爬虫领域的Puppeteer vs. Playwright
爬虫·网络协议·测试工具·接口隔离原则
zxanz113 小时前
SSL 证书申请下来快吗?
网络·网络协议·ssl
网络小江16 小时前
上网第五十二课:加密隧道与拨号专网——安全接入的通俗解释
网络协议
盛世宏博智慧档案18 小时前
TCP以太网温湿度传感器:从RS485痛点突围到工业组网实战
网络·网络协议·tcp/ip
AIFQuant19 小时前
Python A股实时行情API接入:沪深股票数据与WebSocket推送实战
开发语言·python·websocket·金融·a股行情
wdfk_prog19 小时前
LWIP教程 13:从 `dhcp_start()` 到 `DHCP_STATE_BOUND`——DHCPv4、ACD、Timer 与真实抓包
运维·网络协议