Files
docker-build-moo-rist/StatsServerSender.py
2025-12-22 06:32:34 +01:00

79 lines
2.5 KiB
Python

from http.server import BaseHTTPRequestHandler, HTTPServer
import os
from pathlib import Path
import asyncio
import websockets
import threading
HTTP_ADDR = os.getenv('env_http_addr', '0.0.0.0')
HTTP_PORT = int(os.getenv('env_http_port', '8080'))
WS_PORT = int(os.getenv('env_ws_port', '8081'))
LOGFILE_PATH = os.getenv('env_logfile_path', 'logfile.json')
json_string = '{"sender-stats":null}'
async def handler(websocket, path):
global json_string
while True:
await asyncio.sleep(0.5)
if Path.exists(Path(LOGFILE_PATH)):
with open(LOGFILE_PATH, 'r') as f:
json_string = f.read()
if(json_string != '{"sender-stats":null}'):
reply = f"{json_string}"
await websocket.send(reply)
class StatsServer(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
def log_message(self, format, *args):
# Override to prevent logging
return
def do_HEAD(self):
self._set_headers()
def do_GET(self):
self._set_headers()
global json_string
if Path.exists(Path(LOGFILE_PATH)):
with open(LOGFILE_PATH, 'r') as f:
json_string = f.read()
byte_json_string_utf8 = json_string.encode('utf-8')
self.wfile.write(byte_json_string_utf8)
def run_http_server():
server_address = (HTTP_ADDR, HTTP_PORT)
httpd = HTTPServer(server_address, StatsServer)
print(f'Starting HTTP server at http://{HTTP_ADDR}:{HTTP_PORT}...')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print('HTTP server stopped.')
if __name__ == "__main__":
print(Path("banner.txt").read_text())
if Path.exists(Path(LOGFILE_PATH)):
with open(LOGFILE_PATH, 'r') as f:
json_string = f.read()
# Start HTTP server in a separate thread
http_thread = threading.Thread(target=run_http_server)
http_thread.start()
# Setup and run the WebSocket server
async def start_websocket_server():
async with websockets.serve(handler, HTTP_ADDR, WS_PORT):
print(f'WebSocket server started on ws://{HTTP_ADDR}:{WS_PORT}')
await asyncio.Future() # Keep the server running
try:
asyncio.run(start_websocket_server())
except KeyboardInterrupt:
print('WebSocket server stopped.')