技巧之如何快速使用websocket来监控标准输出

为啥是Websocket

  • 服务端可以主动推送消息到浏览器端。比如服务端实时在打印日志,这是一个标准输出,可以实时将日志推送到浏览器。

为啥用websocketd (https://github.com/joewalnes/websocketd)

  • 后台脚本不限语言,标准输入(stdin)就是 WebSocket 的输入,标准输出(stdout)就是 WebSocket 的输出。(http://www.ruanyifeng.com/blog/2017/05/websocket.html)

举例

  • 定时打印当前时间
import datetime,timefrom sys import stdoutwhile True: now = time.strftime("%Y-%m-%d %H:%M:%S") print now stdout.flush() time.sleep(2)
  • 这是标准输出
root@ubuntu:~# python test.py 2018-12-17 09:57:372018-12-17 09:57:392018-12-17 09:57:412018-12-17 09:57:432018-12-17 09:57:452018-12-17 09:57:47
  • 启动websocketd
root@ubuntu:~# websocketd --port=9000 python test.py 
  • 浏览器连接websocketd服务
<!DOCTYPE html><html> <head> <title>websocketd example</title> <style> #count { font: bold 150px arial; margin: auto; padding: 10px; text-align: center; } </style><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body><table border="1px #ooo" id="logtable" cellpadding="0" cellspacing="0" width="30%"> <tr align="center"> <td width="100%">log</td> </tr> </table> <script> function addTr(tab, row, trHtml){ var $tr=$("#"+tab+" tr").eq(row); if($tr.size()==0){ alert("id not exit"); return; } $tr.after(trHtml); }; //addTr(‘logtable‘, -1, ‘xxxxxxxxxx‘); var ws = new WebSocket(‘ws://‘ + (location.host ? location.host : "localhost:9000") + "/"); ws.onopen = function() { document.body.style.backgroundColor = ‘#cfc‘; }; ws.onclose = function() { document.body.style.backgroundColor = null; }; ws.onmessage = function(event) { console.log(event.data); //document.getElementById(‘count‘).textContent = event.data; addTr(‘logtable‘, -1, ‘<tr><td>‘ + event.data + ‘</td></tr>‘) }; </script> </body></html>
  • 效果图

相关文章