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)
})
相关推荐
Sheffield3 天前
Docker的跨主机服务与其对应的优缺点
linux·网络协议·docker
YuMiao7 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Jony_10 天前
高可用移动网络连接
网络协议
chilix10 天前
Linux 跨网段路由转发配置
网络协议
gihigo199812 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
百锦再12 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
白太岁12 天前
通信:(5) 电路交换、报文交换与分组交换
运维·服务器·网络·网络协议
小扎仙森12 天前
关于阿里云实时语音翻译-Gummy推送WebSocket
websocket·阿里云·云计算
EasyGBS12 天前
国标安全升级:GB28181平台EasyGBS支持GB35114协议的应用场景与核心优势
网络协议·安全·gb28181·gb35114
凯酱12 天前
Windows防火墙入站规则IP白名单
windows·网络协议·tcp/ip