• 周四. 4月 25th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

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

admin

11月 28, 2021

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 }

《Django3 channels websocket实时读取日志返回前端》有2个想法
  1. Wow, marvelous weblog format! How long have you ever been running a blog
    for? you made blogging glance easy. The full glance of your site is wonderful,
    let alone the content! You can see similar here sklep online

  2. Do you mind if I quote a couple of your posts as long as I
    provide credit and sources back to your site? My blog is in the exact same niche as yours and my users would
    truly benefit from a lot of the information you provide
    here. Please let me know if this alright with you. Thanks a lot!
    I saw similar here: Najlepszy sklep

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注