python实现http-pingserver
环境:python2.7
平时经常要测试http端口网络是否畅通,centos7的服务器系统一般都带有python2的环境,写了一个基于python2的http协议的ping服务器。
import json
import sys
import urllib
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class HttpHandler(BaseHTTPRequestHandler):
def _response(self, path, args):
code = 200
rtv = {'path': path,
'args': args,
'message': 'pong'}
rtv = json.dumps(rtv, ensure_ascii=False)
self.send_response(code)
self.send_header('Content-type', 'text/json; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(rtv.encode())
def do_GET(self):
path, args = urllib.splitquery(self.path)
self._response(path, args)
def do_POST(self):
args = self.rfile.read(int(self.headers['content-length'])).decode("utf-8")
self._response(self.path, args)
port = 8081
if sys.argv.__len__() > 0:
port = sys.argv[1]
port = int(port)
httpd = HTTPServer(('0.0.0.0', port), HttpHandler)
httpd.serve_forever()
使用方法:
将代码保存到pingServer.py文件中,使用下面的命令开启服务.
python pingServer.py 80