• WebSocket实现方式


    1.安装组件channels

    pip install channels

    2.注册app

    daphne

    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',
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    3.在setting中添加ASGI——APPLICATION
    WSGI_APPLICATION = 'MyBlog.wsgi.application'
    ASGI_APPLICATION = 'MyBlog.wsgi.application'
    
    • 1
    • 2
    4.在app01中创建consumers.py文件
    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    5.在setting.py同级目录中创建routing.py文件
    from django.urls import re_path
    
    from app01 import consumers
    
    websocket_urlpatterns = [
        re_path(r'ws/(?P\w+)/$', consumers.ChatConsumer.as_asgi()),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    6.修改asgi.py文件
    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)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    2022.8.9考试独特的投标拍卖--800题解
    跨境电商迎来全球5日达革命?菜鸟全球化再提速!
    MyBatis--获取参数值
    常用面试/笔试开源小项目21~30
    [网络安全] PKI
    java考试系统课程设计
    对称和非对称加密
    html+css+js实现简单的交互效果
    【Multiwfn学习】-Multiwfn批量读入xyz结构文件并生成ORCA输入文件
    conda安装与镜像源配置
  • 原文地址:https://blog.csdn.net/qq_64585761/article/details/133429162