|
| 1 | +import uasyncio as asyncio |
| 2 | +import sys |
| 3 | +from contextlib import suppress |
| 4 | +import aiohttp |
| 5 | +import _thread |
| 6 | + |
| 7 | +# Shared buffer for input lines |
| 8 | +input_buffer = [] |
| 9 | +lock = _thread.allocate_lock() # Thread-safe access to buffer |
| 10 | + |
| 11 | +# Thread function to read input and add to buffer |
| 12 | +def read_input_thread(): |
| 13 | + while True: |
| 14 | + line = input() |
| 15 | + with lock: |
| 16 | + input_buffer.append(line) |
| 17 | + if line == "exit": |
| 18 | + break |
| 19 | + |
| 20 | +async def start_client(url: str) -> None: |
| 21 | + name = input("Please enter your name: ") |
| 22 | + |
| 23 | + # Start the input reading thread |
| 24 | + _thread.start_new_thread(read_input_thread, ()) |
| 25 | + |
| 26 | + async def dispatch(ws: aiohttp.ClientWebSocketResponse) -> None: |
| 27 | + while True: |
| 28 | + #msg = await ws.receive() |
| 29 | + msg = await ws.__anext__() |
| 30 | + |
| 31 | + if msg.type is aiohttp.WSMsgType.TEXT: |
| 32 | + print("Text: ", msg.data.strip()) |
| 33 | + elif msg.type is aiohttp.WSMsgType.BINARY: |
| 34 | + print("Binary: ", msg.data) |
| 35 | + elif msg.type is aiohttp.WSMsgType.PING: |
| 36 | + await ws.pong() |
| 37 | + elif msg.type is aiohttp.WSMsgType.PONG: |
| 38 | + print("Pong received") |
| 39 | + else: |
| 40 | + if msg.type is aiohttp.WSMsgType.CLOSE: |
| 41 | + await ws.close() |
| 42 | + elif msg.type is aiohttp.WSMsgType.ERROR: |
| 43 | + print("Error during receive %s" % ws.exception()) |
| 44 | + elif msg.type is aiohttp.WSMsgType.CLOSED: |
| 45 | + pass |
| 46 | + break |
| 47 | + |
| 48 | + async with aiohttp.ClientSession() as session: |
| 49 | + async with session.ws_connect(url) as ws: |
| 50 | + dispatch_task = asyncio.create_task(dispatch(ws)) |
| 51 | + |
| 52 | + # Poll the input buffer instead of to_thread |
| 53 | + while True: |
| 54 | + line = None |
| 55 | + with lock: |
| 56 | + if input_buffer: # Check if there's input |
| 57 | + line = input_buffer.pop(0) # Get the first line |
| 58 | + if line: |
| 59 | + await ws.send_str(name + ": " + line) |
| 60 | + if line == "exit": # Stop on "exit" |
| 61 | + break |
| 62 | + await asyncio.sleep_ms(100) # Avoid busy-waiting |
| 63 | + |
| 64 | + dispatch_task.cancel() |
| 65 | + with suppress(asyncio.CancelledError): |
| 66 | + await dispatch_task |
| 67 | + |
| 68 | +# Run the client |
| 69 | +asyncio.run(start_client("wss://echo.websocket.events")) |
0 commit comments