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") stdio: tuple(int, int) = os.pipe2() worker: subprocess.Popen = subprocess.Popen(["python3", "TimeWaster.py"], stdin=stdio[0], stdout=stdio[1]) connected: bool = True task: asyncio.Task = None while (connected): raw: str = await connection.recv() os.write(stdio[1], bytes("job")) if task != None and task.cancel(): print("TASK CANCELED") task = asyncio.create_task(self.respond(raw, connection)) async def respond(self, raw: str, connection: ServerConnection) -> None: message = json.loads(raw) print(f"Received: {message["message"]} width id {message["ID"]}") await asyncio.sleep(random.randrange(1, 10) / 10) response = {"ID": message["ID"], "message": f"received: {message["message"]}"} 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")