diff --git a/giambio/io.py b/giambio/io.py index 01a853a..a5cb425 100644 --- a/giambio/io.py +++ b/giambio/io.py @@ -191,6 +191,8 @@ class AsyncSocket: Wrapper socket method """ + if not hasattr(self.sock, "do_handshake"): + return while True: try: return self.sock.do_handshake() diff --git a/tests/chatroom_client.py b/tests/chatroom_client.py new file mode 100644 index 0000000..80ac22e --- /dev/null +++ b/tests/chatroom_client.py @@ -0,0 +1,57 @@ +import sys +from typing import Tuple +import giambio +import logging + + +async def sender(sock: giambio.socket.AsyncSocket, q: giambio.Queue): + while True: + await sock.send_all(b"yo") + await q.put((0, "")) + + +async def receiver(sock: giambio.socket.AsyncSocket, q: giambio.Queue): + data = b"" + buffer = b"" + while True: + while not data.endswith(b"\n"): + data += await sock.receive(1024) + data, rest = data.split(b"\n", maxsplit=2) + buffer = b"".join(rest) + await q.put((1, data.decode())) + data = buffer + + +async def main(host: Tuple[str, int]): + """ + Main client entry point + """ + + queue = giambio.Queue() + async with giambio.create_pool() as pool: + async with giambio.socket.socket() as sock: + await sock.connect(host) + await pool.spawn(sender, sock, queue) + await pool.spawn(receiver, sock, queue) + while True: + op, data = await queue.get() + if op == 0: + print(f"Sent.") + else: + print(f"Received: {data}") + + +if __name__ == "__main__": + port = int(sys.argv[1]) if len(sys.argv) > 1 else 1501 + logging.basicConfig( + level=20, + format="[%(levelname)s] %(asctime)s %(message)s", + datefmt="%d/%m/%Y %p", + ) + try: + giambio.run(main, ("localhost", port)) + except (Exception, KeyboardInterrupt) as error: # Exceptions propagate! + if isinstance(error, KeyboardInterrupt): + logging.info("Ctrl+C detected, exiting") + else: + logging.error(f"Exiting due to a {type(error).__name__}: {error}") diff --git a/tests/chatroom.py b/tests/chatroom_server.py similarity index 98% rename from tests/chatroom.py rename to tests/chatroom_server.py index 1a18670..b3e31bb 100644 --- a/tests/chatroom.py +++ b/tests/chatroom_server.py @@ -48,7 +48,6 @@ async def handler(sock: AsyncSocket, client_address: tuple): async with sock: # Closes the socket automatically await sock.send_all(b"Welcome to the chartoom pal, start typing and press enter!\n") while True: - await sock.send_all(b"-> ") data = await sock.receive(1024) if not data: break @@ -62,6 +61,7 @@ async def handler(sock: AsyncSocket, client_address: tuple): await client_sock.send_all(data) logging.info(f"Sent {data!r} to {i} clients") logging.info(f"Connection from {address} closed") + clients.remove(sock) if __name__ == "__main__": diff --git a/tests/queue.py b/tests/queue.py index 571774b..d8dc4bb 100644 --- a/tests/queue.py +++ b/tests/queue.py @@ -28,5 +28,5 @@ async def main(q: giambio.Queue, n: int): -queue = giambio.Queue(1) +queue = giambio.Queue() giambio.run(main, queue, 5, debugger=())