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)
})
相关推荐
自己的九又四分之三站台14 小时前
TCP 与 UDP:从可靠字节流到无连接数据报,怎么选、怎么测
网络协议·tcp/ip·udp
wangbing112515 小时前
开发指南147-WebSocket-前端
前端·websocket·网络协议
要吃这碗饭1 天前
深入理解 TCP 协议:从三次握手到可靠传输
网络·网络协议·tcp/ip
Zelman1 天前
HTTPS 协议
网络协议·https
JVM高并发1 天前
使用 Cloudflare Tunnel(本地管理隧道)搭配 DigitalPlat 免费域名实现内网穿透
网络协议·全栈
Zelman1 天前
网络协议性能调优手册
网络协议·性能优化
Zelman1 天前
TCP-IP 协议栈设计哲学
网络协议
阿钱真强道1 天前
28 嵌入式操作系统 | 网关加 TCP 命令通道:粘包/半包怎么切
网络·网络协议·tcp/ip·粘包
hasty1 天前
一次 WebSocket 握手为何能终止进程?Undici CVE-2026-19534 的异常边界
网络·websocket·网络协议
hasty2 天前
前缀相同不代表同一网络:ip-address 跨地址族比较缺陷
网络·网络协议·tcp/ip