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)
})
相关推荐
子兮曰12 小时前
WebSocket 连接:实现实时双向通信的前端技术
前端·javascript·websocket
2301_7720935612 小时前
tuchuang_后端_前端_注册登录
数据库·后端·网络协议·mysql·wireshark
程序员三明治15 小时前
HTTPS 真的牢不可破吗?—— 中间人攻击与安全机制解析
网络协议·安全·https
2501_9151063217 小时前
CDN 可以实现 HTTPS 吗?实战要点、部署模式与真机验证流程
网络协议·http·ios·小程序·https·uni-app·iphone
shixian103041118 小时前
Django 学习日志
数据库·学习·sqlite
千里马-horse18 小时前
HTTP、WebSocket、XMPP、CoAP、MQTT、DDS 六大协议在机器人通讯场景应用
mqtt·websocket·http·机器人·xmpp·coap·fastdds
夕泠爱吃糖1 天前
TCP三次握手四次挥手
网络·网络协议·tcp/ip
TeleostNaCl1 天前
如何在 Windows 上使用命令设置网卡的静态 IP 地址
网络·windows·经验分享·网络协议·tcp/ip·ip
XUE-52113141 天前
组播实验-IGMP、IGMP Snooping及PIM-DM协议
运维·网络·网络协议·智能路由器
liulilittle1 天前
OPENPPP2 静态隧道链路迁移平滑(UDP/IP)
开发语言·网络·c++·网络协议·tcp/ip·udp·通信