From 7156fbc37866436bcc222a9a311dd43f1041ae02 Mon Sep 17 00:00:00 2001 From: nolan Date: Tue, 23 Sep 2025 23:41:01 -0400 Subject: [PATCH] Worked on reorganizing client (doesn't work right now) --- client.py | 44 +++++++++++++++++++++++++++++++++++--------- server.py | 14 ++++++++------ 2 files changed, 43 insertions(+), 15 deletions(-) diff --git a/client.py b/client.py index 1ac312e..7dd90ad 100644 --- a/client.py +++ b/client.py @@ -1,14 +1,40 @@ from websockets import * -import asyncio, json +import asyncio, json, sys -async def msg(): #TODO: Get rid of this boring boilerplate code - uri: str = "ws://127.0.0.1:8765" - async with connect(uri) as websocket: - send: str = input() - await websocket.send(send) - print(f"Client sent {send}") - response: str = await websocket.recv() +class TestClient: + def __init__(self) -> None: + self.connection: ClientConnection = None + + def main(self) -> None: + asyncio.run(self.connect()) + asyncio.run(self.receive()) + + async def connect(self, address: str = "127.0.0.1", port: int = 8765) -> None: + uri: str = f"ws://{address}:{port}" + async with connect(uri) as ws: + self.connection = ws + loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() + loop.add_reader(0, self.message) + await self.connection.wait_closed() + + async def disconnect(self): + await self.connection.close() + self.connection = None + + def message(self) -> None: + text = sys.stdin.readline() + diction: dict = {"message": text} + msg = json.dumps(diction) + asyncio.run(self.__message__(msg)) + + async def __message__(self, msg) -> None: + await self.connection.send(msg) + print(f"Client sent {msg}") + + async def receive(self) -> None: + response: str = await self.connection.recv() print(f"Received: {response}") if __name__ == "__main__": - asyncio.run(msg()) + client = TestClient() + client.main() diff --git a/server.py b/server.py index 81d4fd3..1ac1f80 100644 --- a/server.py +++ b/server.py @@ -16,12 +16,14 @@ class WebSocketServer: await self.server.wait_closed() async def handleConnection(self, connection: ServerConnection) -> None: #TODO: Make this actually do something - print(connection.remote_address) - message: str = await connection.recv() - print(f"Server received: {message}") - response: str = f"Hello {connection.id}. You sent {message}" - await connection.send(response) - print(f"Server replied: {response}") + print(f"{connection.remote_address} Connected") + connected: bool = True + while (connected): + raw: str = await connection.recv() + message = json.loads(raw) + print(f"Received: {message}") + await connection.send('{"message":"received"}') + print("Server replied") def serverController(self) -> None: #TODO: Make ways of actually controlling the server with this print("Server controller. Now die")