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

为啥是Websocket

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

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

举例

  • 定时打印当前时间
import datetime,time
from sys import stdout
while 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:37
2018-12-17 09:57:39
2018-12-17 09:57:41
2018-12-17 09:57:43
2018-12-17 09:57:45
2018-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>
  • 效果图

posted @ 2018-12-18 02:00  小小leo  阅读(1386)  评论(0编辑  收藏  举报