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)
})
相关推荐
可爱系程序猿8 小时前
网络打印机地址正常却无法出纸:从 TCP/IP 端口到 Print Spooler 的排错步骤
网络·网络协议·tcp/ip
liulilittle13 小时前
UCP 控制协议 [简述]
网络·网络协议·计算机网络·udp·ip·通信
Yan_chen66616 小时前
SSH(Secure Shell)安全外壳协议详解
运维·网络协议·ssh
GIR12318 小时前
研究更新:2026年网络协议分析工具发展前景与竞争格局报告(附市场占有率与产业链图谱)
网络·网络协议
贾天佑忆月 迷失的昵18 小时前
客户端与服务器持续同步解析(轮询,comet,WebSocket)
运维·服务器·websocket
半支烟隐 pzishuo20 小时前
HTTP Live Streaming(HLS)直播技术分析与实现
网络·网络协议·http
颜挺锐1 天前
JMeter TCP 取样器 行尾字节值是 62,是代表的什么意思?
网络协议·tcp/ip·jmeter
Yan_chen6661 天前
HTTP和HTTPS 完整指南
网络协议·web安全·http·网络安全·https
蜡台1 天前
Flutter HTTP 请求完整详解
网络协议·flutter·http·dart
OSMeteor1 天前
在 Hyper-V 中搭建固定 IP、固定网关、可上网且与宿主机互通的 Ubuntu 环境
网络协议·tcp/ip·ubuntu