websocket启动流程

from django.test import TestCase

# Create your tests here.

"""
# 一
安装 pip install channels
# 二
settings配置
# 1.app注册
INSTALLED_APPS = [
    'channels',
]

# 2. 配置变量
ASGI_APPLICATION = "qq_chart.asgi.application"
ASGI_APPLICATION = '当前项目名同名的文件名.asgi.application'

# 3.修改asgi文件(默认不支持websocket,只支持http)
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from . import routings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qq_chart.settings')

# application = get_asgi_application()
application = ProtocolTypeRouter({
    'http':get_asgi_application(),
    'websocket':URLRouter(routings.websocket_urlpatterns)
})

# 4.在settings.py同级目录下创建routings.py 路由
from django.urls import re_path
from app01 import consumers

websocket_urlpatterns = [
    re_path(r'ws/(?P<group>\w+)/$', consumers.ChatConsumer.as_asgi())
]

# 5.创建websocket视图 consumers
from channels.exceptions import StopConsumer
from channels.generic.websocket import WebsocketConsumer
# 异步改成同步
from asgiref.sync import async_to_sync


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        '''客户端请求建立链接时 自动触发'''
        self.accept()  # 建立链接  并且自动帮你维护每一个客户端

    def websocket_receive(self, message):
        '''客户端发送数据过来  自动触发'''
        print(message)
        self.send('小心电信诈骗')

    def websocket_disconnect(self, message):
        '''客户端断开链接之后  自动触发'''
        print('断开链接')
        raise StopConsumer()
"""

 

posted @ 2021-11-22 19:20  mofr  阅读(360)  评论(0)    收藏  举报