后端
安装模块
- channels==2.1.5
- channels-Redis==2.3.1
- anyjson==0.3.3
- asgi-Redis==1.4.3
- asgiref==2.3.0
- asn1crypto==0.24.0
- async-timeout==2.0.1
- Twisted==18.9.0
启动一个 Redis
新建 django 程序 quan
目录结构
- quan
- quan
- asgi.py
- consumers.py
- routing.py
- settings.py
settings.py
- INSTALLED_APPS = [
- 'channels',
- ]
- # django-channels 配置
- CHANNEL_LAYERS = {
- "default": {
- "BACKEND": "channels_redis.core.RedisChannelLayer",
- "CONFIG": {
- "hosts": [("127.0.0.1", 6379)],
- },
- },
- }
- # 配置 ASGI
- ASGI_APPLICATION = "quan.routing.application"
asgi.py
- import os
- import django
- from channels.routing import get_default_application
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "quan.settings")
- django.setup()
- application = get_default_application()
consumers.py
- from asgiref.sync import async_to_sync
- from channels.generic.websocket import WebsocketConsumer
- from channels.layers import get_channel_layer
- channel_layer = get_channel_layer()
- import JSON
- import time
- class ExecConsumer(WebsocketConsumer):
- def connect(self):
- print('ws 连接')
- # 创建 channels group, 命名为: 用户名, 并使用 channel_layer 写入到 Redis
- async_to_sync(self.channel_layer.group_add)(self.scope['user'].username, self.channel_name)
- # 返回给 receive 方法处理
- self.accept()
- def receive(self, text_data):
- id_list = eval(text_data)
- data = {'1':99}
- async_to_sync(self.channel_layer.group_send)(
- self.scope['user'].username,
- {
- "type": "user.message",
- "text": JSON.dumps(data),
- },
- )
- def user_message(self, event):
- # 消费
- self.send(text_data=event["text"])
- def disconnect(self, close_code):
- print("关闭 ws")
- async_to_sync(self.channel_layer.group_discard)(self.scope['user'].username, self.channel_name)
routing.py
- from channels.auth import AuthMiddlewareStack
- from channels.routing import URLRouter, ProtocolTypeRouter
- from django.urls import path
- from .consumers import ExecConsumer
- application = ProtocolTypeRouter({
- "websocket": AuthMiddlewareStack(
- URLRouter([
- path(r"progress/", ExecConsumer),
- ])
- )
- })
前端
- <script>
- var socket = new WebSocket('ws://' + Windows.location.host + '/progress/');
- var id_list = [];
- $(".dataTables").find("tr").each(function () {
- var tdArr = $(this).children();
- var id = tdArr.eq(0).text();
- id_list.push(id)
- });
- id_list.splice(0, 1);
- var to = function () {
- socket.send(id_list);
- };
- socket.onopen = function () {
- setInterval(to, 1000);
- };
- // 获得消息事件
- socket.onmessage = function (msg) {
- console.log(msg.data);
- var data = msg.data;
- var obj = JSON.parse(data);
- $.each(obj, function (key, val) {
- $('#' + key).children('td').eq(7).html(val + '%')
- });
- };
- // 关闭事件
- socket.onclose = function () {
- {#alert("Socket 已关闭");#}
- };
- // 发生了错误事件
- socket.onerror = function () {
- {#alert("发生了错误");#}
- }
- </script>
来源: http://www.bubuko.com/infodetail-2863258.html