基于python的websocket开发,tomcat日志web页面实时打印监控案例

web socket 接收器:webSocket.py 

相关依赖

# pip install bottle gevent gevent-websocket argparse
from bottle import request, Bottle, abort
from geventwebsocket import WebSocketError
from gevent.pywsgi import WSGIServer
from flask import request
from geventwebsocket.handler import WebSocketHandler
from bottle import get, post, request
app = Bottle()
users = {}
@app.get('/websocket/<token>/<senduser>')
def handle_websocket(token,senduser):
    wsock = request.environ.get('wsgi.websocket')
    users[token] = wsock
    if not wsock:
        abort(400, 'Expected WebSocket request.')
    while True:
        try:
            message = wsock.receive()
        except WebSocketError:
            breakif message:
try:
                users[senduser].send(message)
           except WebSocketError:
                print u'kill'
server = WSGIServer(("0.0.0.0", 1019), app,handler_class=WebSocketHandler)
server.serve_forever()

 

服务端:logs.py

相关依赖:

pip install websocket-client
import subprocess
from websocket import create_connection
ws_server = "ws://172.18.30.19:1010/websocket/<token>/<senduser>" 
ws = create_connection(ws_server) command='sshpass -p 123456 ssh 192.168.20.200 -p 32776 -o StrictHostKeychecking=no "tail -f /root/tomcat-8.0/logs/catalina.out"'
popen=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

while True:
line=popen.stdout.readline().strip()
ws.send(line)

应用前端:logs.html

<!DOCTYPE html>
<html>
<head>
    <title>LOG+</title>
    <style>
        html, body {
            font: normal 0.9em arial, helvetica;
        }
        #log {
            width: 440px;
            height: 200px;
            border: 1px solid #7F9DB9;
            overflow: auto;
        }
        #msg {
            width: 330px;
        }
    </style>
    <script>
        var socket;
        function init() {
            var host = "ws://172.18.30.19:1010/websocket/<token>/<senduser>";
            try {
                socket = new WebSocket(host);
                socket.onopen = function (msg) {
                    log('Connected');
                };
                socket.onmessage = function (msg) {
                    log(msg.data);
                };
                socket.onclose = function (msg) {
                    log("Lose Connection!");
                };

     socket.onerror = function(msg) {
      log("websocket error!");
                };

            }
            catch (ex) {
                log(ex);
            }
            $("msg").focus();
        }
        function send() {
            var txt, msg;
            txt = $("msg");
            msg = txt.value;
            if (!msg) {
                alert("Message can not be empty");
                return;
            }
            txt.value = "";
            txt.focus();
            try {
                socket.send(msg);
            } catch (ex) {
                log(ex);
            }
        }
        window.onbeforeunload = function () {
            try {
                socket.send('quit');
                socket.close();
                socket = null;
            }
            catch (ex) {
                log(ex);
            }
        };
        function $(id) {
            return document.getElementById(id);
        }
        function log(msg) {
            $("log").innerHTML += "<br>" + msg;
        }
        function onkey(event) {
            if (event.keyCode == 13) {
                send();
            }
        }
    </script>
</head>
<body οnlοad="init()">
<h3>WebSocket</h3>
<br><br>
<div id="log"></div>
<input id="msg" type="textbox" οnkeypress="onkey(event)"/>
<button οnclick="send()">发送</button>
</body>
</html>

测试一把:

结束语:

前端 ——》 接收器  《—— 服务端

 

以需求用例为基,Case&Coding两条线并行,服务(M)&消费(VC)分离,单元、接口、功能、集成四层质量管理,自动化集成、测试、交付全程支持。 3个大阶段(需求分析阶段、研发准备阶段、研发测试阶段)16个小历程(*)确定好边界,明确好对接产物,做好服务管理。

 

在使用这段python代码之前,先在安装以下模块:

pip install gevent-websocket

pip install gevent

pip install bottle

 
  1. from bottle import request, Bottle, abort
  2. from geventwebsocket import WebSocketError
  3. from gevent.pywsgi import WSGIServer
  4. from geventwebsocket.handler import WebSocketHandler
  5. app = Bottle()
  6. users = set()
  7. @app.get('/websocket/')
  8. def handle_websocket():
  9.     wsock = request.environ.get('wsgi.websocket')
  10.     users.add(wsock)
  11.     if not wsock:
  12.         abort(400, 'Expected WebSocket request.')
  13.     while True:
  14.         try:
  15.             message = wsock.receive()
  16.         except WebSocketError:
  17.             break
  18.         print u"现有连接用户:%s" % (len(users))
  19.         if message:
  20.             for user in users:
  21.                 try:
  22.                     user.send(message)
  23.                 except WebSocketError:
  24.                     print u'某用户已断开连接'
  25.     # 如果有客户端断开,则删除这个断开的websocket
  26.     users.remove(wsock)
  27. server = WSGIServer(("0.0.0.0", 8000), app,handler_class=WebSocketHandler)
  28. server.serve_forever()

 

这2篇文章的websocket服务端代码,都差不多,只是用的模块不一样而已,前者用的是bottle-websocket扩展包,此篇用的是gevent-websocket包

其实还可以用websocket,开发成一个聊天室的,很简单,只是html和javascripts要多开发点功能而已,有兴趣的自己试试

 

如何在python终端中调试呢,先要安装一个python的websocket-client包(pip install websocket-client),以下是相关的调试代码:

 
  1. >>> from websocket import create_connection
  2. >>> ws_server = "ws://192.168.1.221:8000/websocket/"
  3. >>> ws = create_connection(ws_server)
  4. >>> ws.send('hello,http://www.linuxyw.com')  #发送数据
  5. 34
  6. >>> ws.recv()  #获取数据
  7. 'hello,http://www.linuxyw.com'
  8. >>> ws.send('欢迎光临我的博客')
  9. 30
  10. >>> ws.recv()
  11. '\xe6\xac\xa2\xe8\xbf\x8e\xe5\x85\x89\xe4\xb8\xb4\xe6\x88\x91\xe7\x9a\x84\xe5\x8d\x9a\xe5\xae\xa2'

send("内容") :是发送数据给websocket服务端

recv() : 是从websocket服务端获取数据

转载于:https://www.cnblogs.com/Javame/p/6559969.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值