PyWebSockets/client.py

41 lines
1.2 KiB
Python

from websockets import *
import asyncio, json, sys
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__":
client = TestClient()
client.main()