tomcat日志web页面实时打印监控案例,WebSocket长连

2019-12-23 08:44栏目:网络编程
TAG:

ws=websocket.WebSocketApp("wss://*********",on_message=on_message,on_error=on_error,on_close=on_close)

先来看一下,长连接调用方式:

图片 1

ws.on_open=on_openws.run_forever()提示SSLnotavailable我修改成ws.run_forever(sslopt={"cert_reqs":ssl.CERT_NONE})也一样提示SSLnotavailable有人知道是什么问题吗?我用js是可以正常连接websocket的

(5)on_error:这个对象在遇到错误时调用,有两个参数,第一个是该类本身,第二个是异常对象。

 

 

结束语:

 

 

长连接关键方法:ws.run_forever(ping_interval=60,ping_timeout=5)

            }
            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 onload="init()">
<h3>WebSocket</h3>
<br><br>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">发送</button>
</body>
</html>

示例1:

  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,')  #发送数据
  5. 34
  6. >>> ws.recv()  #获取数据
  7. 'hello,'
  8. >>> ws.send('欢迎光临我的博客')
  9. 30
  10. >>> ws.recv()
  11. 'xe6xacxa2xe8xbfx8exe5x85x89xe4xb8xb4xe6x88x91xe7x9ax84xe5x8dx9axe5xaexa2'
ws.run_forever(ping_interval=60,ping_timeout=5)

#ping_interval心跳发送间隔时间

#ping_timeout 设置,发送ping到收到pong的超时时间

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

——

相关依赖

(3)on_open:在建立Websocket握手时调用的可调用对象,这个方法只有一个参数,就是该类本身。

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

 

相关依赖:

 

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

 

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

(1)url: websocket的地址。

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

python websocket

pip install gevent-websocket

        if not ping_timeout or ping_timeout <= 0:
            ping_timeout = None
        if ping_timeout and ping_interval and ping_interval <= ping_timeout:
            raise WebSocketException("Ensure ping_interval > ping_timeout")
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)
import websocket
from threading import Thread
import time
import sys


class MyApp(websocket.WebSocketApp):
    def on_message(self, message):
        print(message)

    def on_error(self, error):
        print(error)

    def on_close(self):
        print("### closed ###")

    def on_open(self):
        def run(*args):
            for i in range(3):
                # send the message, then wait
                # so thread doesn't exit and socket
                # isn't closed
                self.send("Hello %d" % i)
                time.sleep(1)

            time.sleep(1)
            self.close()
            print("Thread terminating...")

        Thread(target=run).start()


if __name__ == "__main__":
    websocket.enableTrace(True)
    if len(sys.argv) < 2:
        host = "ws://echo.websocket.org/"
    else:
        host = sys.argv[1]
    ws = MyApp(host)
    ws.run_forever()

 

长连接:

pip install gevent

 

测试一把:

 

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

(8)on_data:当从服务器接收到消息时被调用,有四个参数,分别是:该类本身,接收到的字符串(utf-8),数据类型,连续标志。

<!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!");
                };
import websocket
try:
    import thread
except ImportError:
    import _thread as thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")


def on_open(ws):
    def run(*args):
        ws.send("hello1")
        time.sleep(1)
        ws.close()
    thread.start_new_thread(run,())

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever(ping_interval=60,ping_timeout=5)

pip install bottle

 如果不断开关闭websocket连接,会一直阻塞下去。另外这个函数带两个参数,如果传的话,启动心跳包发送。

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

(6)on_close:在遇到连接关闭的情况时调用,参数只有一个,就是该类本身。

服务端:logs.py

 

应用前端:logs.html

 

# 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()

 

 

 

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

pip install websocket-client

web socket 接收器:webSocket.py 

 

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

(4)on_message:这个对象在接收到服务器返回的消息时调用。有两个参数,一个是该类本身,一个是我们从服务器获取的字符串(utf-8格式)。

 

(11)subprotocols:一组可用的子协议,默认为空。

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

ping的超时时间,要大于ping间隔时间

 

ping_interval:自动发送“ping”命令,每个指定的时间(秒),如果设置为0,则不会自动发送。

 

 长连接,参数介绍:

 

 

    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

 

安装

我们看源代码,会发现这样一断代码:

示例2:

(9)keep_running:一个二进制的标志位,如果为True,这个app的主循环将持续运行,默认值为True。

ping_timeout:如果没有收到pong消息,则为超时(秒)。

 

(7)on_cont_message:这个对象在接收到连续帧数据时被调用,有三个参数,分别是:类本身,从服务器接受的字符串(utf-8),连续标志。

短连接:

from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result =  ws.recv()
print("Received '%s'" % result)
ws.close()

(10)get_mask_key:用于产生一个掩码。

(2)header: 客户发送websocket握手请求的请求头,{'head1:value1','head2:value2'}。

版权声明:本文由澳门新葡亰平台游戏发布于网络编程,转载请注明出处:tomcat日志web页面实时打印监控案例,WebSocket长连