• Django3 channels websocket实时读取日志返回前端


    routing.py

    1 from django.urls import re_path
    2 from . import consumers
    3 
    4 websocket_urlpatterns = [
    5     re_path(r'ws/', consumers.ChatConsumer.as_asgi()),
    6 ]

    consummers.py

     1 # -*- coding: utf-8 -*-
     2 # chat/consumers.py
     3 import json
     4 from channels.generic.websocket import AsyncWebsocketConsumer
     5 import asyncio
     6 import os
     7 
     8 
     9 class ChatConsumer(AsyncWebsocketConsumer):
    10     async def connect(self):
    11         await self.accept()
    12         # g = '/usr/local/nginx/logs/access.log'
    13         # f = open(g)
    14         # while True:
    15         #     await asyncio.sleep(1)
    16         #     message = f.read()
    17         #     print(message)
    18         #     await self.send(text_data=json.dumps({
    19         #         'message': message
    20         #     }))
    21 
    22     async def disconnect(self, code):
    23         await self.close()
    24 
    25     async def receive(self, text_data=None, bytes_data=None):
    26         print(text_data)
    27         # clean log
    28         os.system("echo clean log success > /var/log/ywcontrol.log")
    29         os.system("echo `date` >> /var/log/ywcontrol.log")
    30         os.system("echo Let is get your act together, honey .>> /var/log/ywcontrol.log")
    31         # if text_data == "exp":
    32         g = '/var/log/ywcontrol.log'
    33         f = open(g)
    34         while True:
    35             await asyncio.sleep(2)
    36             message = f.read()
    37             if message:
    38                 try:
    39                     await self.send(text_data=json.dumps({
    40                         'message': message
    41                     }))
    42                 except Exception as e:
    43                     print(e)

    前端html JS部分

     1 const chatSocket = new WebSocket(
     2             'ws://'
     3             + window.location.host
     4             + '/ws/'
     5         );
     6 
     7         chatSocket.onopen = function () {
     8             chatSocket.send("Websocket send data!")
     9               };
    10         chatSocket.onmessage = function(evt) {
    11             console.log('here');
    12             const data = JSON.parse(evt.data);
    13             {#document.getElementById('chat-log').innerText=(data['message']);#}
    14             document.querySelector('#chat-log').value += (data.message + '
    ');
    15         };
    16         chatSocket.onclose = function(e) {
    17             console.error('Chat socket closed unexpectedly');
    18         };
    19         window.onbeforeunload = function () {
    20             chatSocket.close();
    21         };
    22         function closeWebSocket() {
    23             chatSocket.close();
    24 }
  • 相关阅读:
    手机网页版知乎内容隐藏效果的实现
    Egret白鹭开发微信小游戏手机震动功能
    Egret白鹭开发微信小游戏分享功能
    Egret白鹭开发微信小游戏(使用皮肤搭建UI,代码调用组件功能)
    Egret白鹭开发微信小游戏程序跳转功能(由一个小游戏跳转到另一个小游戏)
    Egret白鹭开发小游戏之自定义load加载界面
    unity shader 纹理&透明效果
    unity shader 入门
    unity shader之预备知识
    Unity官方案例精讲_2015_优化
  • 原文地址:https://www.cnblogs.com/changbo/p/15169061.html
Copyright © 2020-2023  润新知