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)
})
相关推荐
绿豆人2 分钟前
RPC项目学习2
网络协议·学习·rpc
ZC跨境爬虫17 分钟前
海南大学交友平台开发实战 day11(实现性别图标渲染与后端数据关联+Debug复盘)
前端·python·sqlite·html·json
帐篷Li1 小时前
创建Controller HTTP测试脚本
网络·网络协议·http
捞的不谈~1 小时前
LUCID相机(HTR003S-001)更改IP地址
网络·网络协议·tcp/ip
傻啦嘿哟3 小时前
住宅IP隧道代理vs数据中心隧道代理:谁更值得买
网络·网络协议·tcp/ip
Lution Young3 小时前
关于IP、子网掩码以及网关
网络·网络协议·tcp/ip
lularible3 小时前
PTP协议精讲(2.8):逐链路精准测量——P2P延迟测量机制详解
网络·网络协议·开源·嵌入式·ptp
TechWayfarer3 小时前
跨境电商IP归属地API实战:如何用IP纯净度检测避开连坐封号?
网络·网络协议·tcp/ip
2401_873479403 小时前
广告反作弊怎么验证IP地理一致性?用IP地址查询工具比对定位即可
网络·网络协议·tcp/ip
指针刺客3 小时前
网络协议之WebSocket
网络·websocket·网络协议