Worked on the client

This commit is contained in:
nolan 2025-09-30 19:23:06 -04:00
parent 7156fbc378
commit d9d3e46d44
3 changed files with 32 additions and 28 deletions

View File

@ -1,40 +1,41 @@
from websockets import *
import asyncio, json, sys
import asyncio, json, prompt_toolkit
class TestClient:
def __init__(self) -> None:
def __init__(self, address: str = "127.0.0.1", port: int = 8765) -> None:
self.connection: ClientConnection = None
self.msgId: int = 0
self.connected = True
asyncio.run(self.main(address, port))
def main(self) -> None:
asyncio.run(self.connect())
asyncio.run(self.receive())
async def main(self, address: str, port: int) -> None:
await self.connect(address, port)
tasks: list[asyncio.Task] = []
async with asyncio.TaskGroup() as tg:
tasks.append(tg.create_task(self.__message__()))
tasks.append(tg.create_task(self.receive()))
print("Finished")
await self.connection.close()
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
self.connection = await connect(uri)
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 __message__(self) -> None:
session = prompt_toolkit.PromptSession()
while (self.connected):
text: str = await session.prompt_async()
print(f"Text: '{text}'")
diction: dict = {"ID": self.msgId, "message": text}
msg = json.dumps(diction)
await self.connection.send(msg)
self.msgId += 1
print(f"Client sent {msg}")
async def receive(self) -> None:
response: str = await self.connection.recv()
print(f"Received: {response}")
while (self.connected):
response: str = await self.connection.recv()
print(f"Received: {response}")
if __name__ == "__main__":
client = TestClient()
client.main()

View File

@ -1,3 +1,5 @@
MarkupSafe==3.0.2
prompt_toolkit==3.0.52
wcwidth==0.2.14
websockets==15.0.1
Werkzeug==3.1.3

View File

@ -21,8 +21,9 @@ class WebSocketServer:
while (connected):
raw: str = await connection.recv()
message = json.loads(raw)
print(f"Received: {message}")
await connection.send('{"message":"received"}')
print(f"Received: {message["message"]} width id {message["ID"]}")
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