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)
})
相关推荐
Remember_99316 小时前
一文吃透Java WebSocket:原理、实现与核心特性解析
java·开发语言·网络·websocket·网络协议·http·p2p
加农炮手Jinx16 小时前
Flutter for OpenHarmony:web_socket_channel 全平台 WebSocket 通信标准库,从原理到鸿蒙实战(3000字深度解析)
android·前端·网络·websocket·flutter·华为·harmonyos
王码码203516 小时前
Flutter for OpenHarmony:stomp_dart_client 打造实时消息引擎(企业级 WebSocket 通信标准) 深度解析与鸿蒙适配指南
网络·websocket·网络协议·flutter·ui·华为·harmonyos
王码码203516 小时前
Flutter for OpenHarmony:web_socket 纯 Dart 标准 WebSocket 客户端(跨平台兼容性之王) 深度解析与鸿蒙
android·前端·websocket·网络协议·flutter·华为·harmonyos
中北萌新程序员16 小时前
WebSocket(看这一篇就够了)
网络·websocket·网络协议
小鹿嘻嘻16 小时前
PaddlePaddle镜像结合WebSocket实现实时推理结果推送
websocket·paddlepaddle·实时推理
EmmaXLZHONG18 小时前
分布式系统概念与设计笔记(Notes of Distributed Systems Concepts and Design)
笔记·分布式·网络协议·计算机网络
cur1es21 小时前
【TCP 协议的相关特性】
java·网络·网络协议·tcp/ip·tcp·滑动窗口·连接管理
qq_454245031 天前
GraphMindStudio 数据操作层解析:基于 SQLite 的封装与自动化存储
sqlite·c#
倚肆1 天前
Spring WebSocket 核心注解详解
java·websocket·spring