-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
73 lines (67 loc) · 2.11 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
import time
import argparse
import tempfile
import subprocess
try:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
except:
from http.server import HTTPServer, BaseHTTPRequestHandler
class HTTPRequestHandler(BaseHTTPRequestHandler):
def _writeheaders(self):
self.send_response(200)
self.send_header('Connection', 'keep-alive')
self.send_header('Content-Type', 'text/event-stream')
self.end_headers()
# GET Method
def do_GET(self):
if self.path == '/':
# prepend the filename with current filepath
path = os.getcwd() + '/index.html'
with open(path) as indexHtml:
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(indexHtml.read().encode())
else:
self._writeheaders()
while True:
f = tempfile.TemporaryFile()
p = subprocess.Popen(['top', '-n', '1'], stdout=f)
time.sleep(2)
p.terminate()
p.wait()
f.seek(0)
chunk = f.read()
# test started
try:
from urllib import quote
except:
from urllib.parse import quote
f.close()
string = 'id: 1\ndata: {}\ndata:\n\n'.format(quote(chunk))
self.wfile.write(bytes(string.encode()))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'-b',
'--bind',
help="The host/address to bind to",
default="127.0.0.1"
)
parser.add_argument(
'-p',
'--port',
type=int,
help="Port number to listen on",
default=8000
)
args = parser.parse_args()
port = args.port
httpd = HTTPServer(('', port), HTTPRequestHandler)
print("Listening at port", port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.server_close()
print("Server stopped")