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)
})
相关推荐
weixin_4250230018 分钟前
Spring Boot 2.7+JDK8+WebSocket对接阿里云百炼Qwen3.5-Plus 实现流式对话+思考过程实时展示
java·spring boot·websocket·ai编程
王家视频教程图书馆18 分钟前
你在 HTTPS 页面 里加载 HTTP 资源 → ,不支持 HTTPS → 握手失败。浏览器自动升级为 HTTPS。你的 8080 端口只支持 HTTP
网络协议·http·https
程序00724 分钟前
在线五子棋小游戏(.NET Core+FreeSql+WebSocket ) html+js
websocket·html·.netcore
Mountain and sea31 分钟前
从一次通讯中断事故说起:Modbus TCP 调试实战与避坑指南
网络·网络协议·tcp/ip·工业机器人
三三有猫15 小时前
代理IP:按流量还是按IP/时长计费更划算?
网络·网络协议·tcp/ip
未来转换16 小时前
计算机网络之HTTP协议详解
网络协议·计算机网络·http
初中就开始混世的大魔王20 小时前
3.1 DDS 层-Core
开发语言·c++·网络协议·tcp/ip·信息与通信
有代理ip1 天前
聚焦性价比:便宜动态IP在网络优化中的应用技巧
网络·网络协议·tcp/ip
wanhengidc1 天前
云手机 流畅稳定 操作简单
服务器·网络·网络协议·安全·智能手机
zl_dfq1 天前
计算机网络 之 【https协议】(数字摘要、密钥、数字证书)
网络协议·计算机网络·https