66 lines
2.8 KiB
Python
66 lines
2.8 KiB
Python
from websockets import *
|
|
from TimeWaster import *
|
|
import asyncio, json, signal, sys, time, random, subprocess, os
|
|
|
|
class WebSocketServer:
|
|
server: Server = None
|
|
|
|
def __init__(self) -> None:
|
|
asyncio.run(self.main())
|
|
|
|
async def main(self) -> None:
|
|
async with serve(self.handleConnection, "", 8765) as sv:
|
|
self.server = sv
|
|
loop: asyncio.AbstractEventLoop = asyncio.get_running_loop()
|
|
loop.add_signal_handler(signal.SIGTERM, self.closeServer)
|
|
loop.add_reader(0, self.serverController)
|
|
await self.server.wait_closed()
|
|
|
|
async def handleConnection(self, connection: ServerConnection) -> None: #TODO: Make this actually do something
|
|
print(f"{connection.remote_address} Connected")
|
|
worker: asyncio.subprocess.Process = await asyncio.create_subprocess_exec("python3", "-u", "TimeWaster.py", stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
|
connected: bool = True
|
|
asyncio.create_task(self.sendResponse(worker, connection))
|
|
asyncio.create_task(self.readErr(worker))
|
|
while (connected):
|
|
raw: str = await connection.recv()
|
|
print(f"Got data: {raw}")
|
|
worker.send_signal(signal.SIGUSR1) #Cancel any existing jobs
|
|
worker.stdin.write(f"{raw}<END>".encode())
|
|
await worker.stdin.drain()
|
|
print(f"Wrote data")
|
|
|
|
async def sendResponse(self, proc: asyncio.subprocess.Process, connection: ServerConnection):
|
|
while (True):
|
|
print("Running sendResponse")
|
|
data = (await proc.stdout.readuntil("<END>".encode()))[:-5]
|
|
print(f"Read \"{data.decode()}\"")
|
|
# await self.respond(data, connection)
|
|
task = asyncio.create_task(self.respond(data, connection))
|
|
|
|
async def readErr(self, proc: asyncio.subprocess.Process):
|
|
data = await proc.stderr.read()
|
|
print(f"ERROR: {data.decode()}")
|
|
exit(1)
|
|
|
|
async def respond(self, raw: str, connection: ServerConnection) -> None:
|
|
message = json.loads(raw)
|
|
print(f"Received: \'{message["result"]}\' with id \'{message["ID"]}\'")
|
|
await asyncio.sleep(random.randrange(1, 10) / 10)
|
|
response = {"ID": message["ID"], "message": f"received: {message["result"]}"}
|
|
await connection.send(json.dumps(response))
|
|
print("Server replied")
|
|
|
|
def serverController(self) -> None: #TODO: Make ways of actually controlling the server with this
|
|
print("Server controller. Now die")
|
|
print(sys.stdin.readline())
|
|
self.closeServer()
|
|
|
|
def closeServer(self) -> None:
|
|
print("Closing down")
|
|
self.server.close()
|
|
|
|
if __name__ == "__main__":
|
|
WebSocketServer()
|
|
print("see ya suckers")
|