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(, '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", ), 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 .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 == ) {
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>

测试一把:

结束语:

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

以需求用例为基,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服务端获取数据

基于python的websocket开发,tomcat日志web页面实时打印监控案例的更多相关文章

  1. 如何优雅的关闭基于Spring Boot 内嵌 Tomcat 的 Web 应用

    背景 最近在搞云化项目的启动脚本,觉得以往kill方式关闭服务项目太粗暴了,这种kill关闭应用的方式会让当前应用将所有处理中的请求丢弃,响应失败.这种形式的响应失败在处理重要业务逻辑中是要极力避免的 ...

  2. Python 全栈开发九 日志模块

    日志是一种可以追踪某些软件运行时所发生事件的方法.软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情.一个事件可以用一个可包含可选变量数据的消息来描述.此外,事件也有重要性的概念 ...

  3. python 实现过滤出tomcat日志中含有ERROR 或Exception 的行并保存在另一个文件

    遍历多个tomcat日志文件,找出含有ERROR 和Exception 的日志,并把该行日志输出到另一个文件中:(这里为了体现python模块导入的知识,所有建立了多个文件夹和模块) 项目结构: co ...

  4. web页面内容打印总结

    web页面打印有两种,一种是直接调用window.print()命令操作,一种是使用ActiveX插件(Object标签)操作,但是第二种只支持IE内核的浏览器. 示例1: <!DOCTYPE ...

  5. 基于Python的Webservice开发(一)-简介

    之前为了解决Webservice的开发,直接用Python自带的CGI模块挂在IIS上. 但是该方式开发Soap的接口,需要大量的开发,而且安全方面也存在很多问题. 我推荐关于用Python开发Web ...

  6. python 全栈开发,Day66(web应用,http协议简介,web框架)

    一.web应用 web应用程序是一种可以通过Web访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要再安装其他软件.应用程序有两种模式C/S.B/S.C/S是客户端 ...

  7. JAVA WEB学习笔记(三):简单的基于Tomcat的Web页面

    注意:每次对Tomcat配置文件进行修改后,必须重启Tomcat 在E盘的DATA文件夹中创建TomcatDemo文件夹,并将Tomcat安装路径下的webapps/ROOT中的WEB-INF文件夹复 ...

  8. 基于Python的Webservice开发(三)-Django安装配置

    一.安装Django pip install django 二.创建项目 进入指定的目录后 django-admin startproject WebApi 目录说明: WebApi 项目的容器. m ...

  9. 基于Python的Webservice开发(二)-如何用Spyne开发Webservice

    一.功能需求 本次案例是开发一个Item的新建的WebService.IN&OUT的类型JsonDocument. 通过传入相关的参数创建Item,且相关的参数可以被缺省. 二.实现代码 引入 ...

随机推荐

  1. noip第13课资料

  2. 查看服务器tcp连接及服务器并发

    一.查看哪些IP连接本机netstat -an二.查看TCP连接数1)统计80端口连接数netstat -nat|grep -i "80"|wc -l 2)统计httpd协议连接数 ...

  3. Centos6.5安装中文支持和中文输入法

     先来讲中文支持:    之前在网上查了不少资料,很多网友在网上都说,在shell命令下输入: # vi /etc/sysconfig/i18n 然后修改LANG="en_US.UTF-8& ...

  4. Delphi使用iTools安卓模拟器

    Delphi使用iTools安卓模拟器 1.去官网下载或https://pc.qq.com/detail/11/detail_22131.html 2.安装后,需要通过设置功能,设置一下分辩率,变成手 ...

  5. git & github 同步文件

    step1 : 在github上建立一个 repository https://github.com/ntu-juking/softwaretesting.git repository name is ...

  6. DWARF 中的 Debug Info 格式

    本周花了几天的时间来研究怎么在 breakpad [1, 2] 中加入打印函数参数的功能,以期其产生的 callstack 更具可读性,方便定位崩溃原因. 现代 ELF 中的调试信息基本是以 DWAR ...

  7. kill 结束进程

    kill 支持的信号 kill -1 重启进程 kill -9 终止进程 pkill 和 killall 的区别在于pkill 可以踢终端用户 pkill  -9  -t tty1

  8. Java线程池(ThreadPoolExecutor)原理分析与使用

    在我们的开发中"池"的概念并不罕见,有数据库连接池.线程池.对象池.常量池等等.下面我们主要针对线程池来一步一步揭开线程池的面纱. 使用线程池的好处 1.降低资源消耗 可以重复利用 ...

  9. 自动化测试框架的Step By Step搭建及测试实战(1)

    1.1什么是自动化测试框架 1.什么是自动化框架 自动化框架是应用与自动化测试的程序框架,它提供了可重用的自动化测试模块,提供最基础的自动化测试功能,或提供自动化测试执行和管理功能的架构模块.它是由一 ...

  10. 关于ASP.Net Core Web及API身份认证的解决方案

    6月15日,在端午节前的最后一个工作日,想起有段日子没有写过文章了,倒有些荒疏了.今借夏日蒸蒸之气,偷得浮生半日悠闲.闲话就说到这里吧,提前祝大家端午愉快(屈原听了该不高兴了:))!.NetCore自 ...