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 + '\n');
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 }

 

上一篇:Spring Boot中使用WebSocket几种实现方式-详解


下一篇:struts2.3.15 WebSocketServlet简单实现