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)
})
相关推荐
wanhengidc31 分钟前
云手机对小说工作室的作用
运维·服务器·网络·网络协议·智能手机
做萤石二次开发的哈哈1 小时前
萤石开放平台音视频 P2P 能力核心是什么?
网络·网络协议·p2p
You Only Live Once_21 小时前
SQLite3部署与配置[WIN11]
数据库·sqlite
天启HTTP1 小时前
HTTP代理和隧道代理的底层区别与适用场景分析
开发语言·网络协议·tcp/ip·php
江畔何人初1 小时前
http协议的概念以及http1,http2,http3的区别
网络·网络协议·http
百撕可乐1 小时前
WenDoraAi官网NextJS实战04:HTTP 请求封装与SSR
前端·网络·网络协议·react.js·http
以太浮标2 小时前
华为eNSP模拟器综合实验之- WLAN瘦AP配置实战案例详解
运维·网络·网络协议·华为·智能路由器·信息与通信
患得患失9492 小时前
【前端websocket】企业级功能清单
前端·websocket·网络协议
半壶清水2 小时前
[软考网规考点笔记]-局域网之高速以太网
网络·笔记·网络协议·考试
芯智工坊2 小时前
第17章 Mosquitto WebSocket支持
网络·websocket·网络协议