| 1 |
#!/usr/bin/env python3 |
| 2 |
"""websocket cmd client for web_ws.py example.""" |
| 3 |
|
| 4 |
import argparse |
| 5 |
import asyncio |
| 6 |
import sys |
| 7 |
from contextlib import suppress |
| 8 |
|
| 9 |
import aiohttp |
| 10 |
|
| 11 |
|
| 12 |
async def start_client(url: str) -> None: |
| 13 |
name = input("Please enter your name: ") |
| 14 |
|
| 15 |
async def dispatch(ws: aiohttp.ClientWebSocketResponse) -> None: |
| 16 |
while True: |
| 17 |
msg = await ws.receive() |
| 18 |
|
| 19 |
if msg.type == aiohttp.WSMsgType.TEXT: |
| 20 |
print("Text: ", msg.data.strip()) |
| 21 |
elif msg.type == aiohttp.WSMsgType.BINARY: |
| 22 |
print("Binary: ", msg.data) |
| 23 |
elif msg.type == aiohttp.WSMsgType.PING: |
| 24 |
await ws.pong() |
| 25 |
elif msg.type == aiohttp.WSMsgType.PONG: |
| 26 |
print("Pong received") |
| 27 |
else: |
| 28 |
if msg.type == aiohttp.WSMsgType.CLOSE: |
| 29 |
await ws.close() |
| 30 |
elif msg.type == aiohttp.WSMsgType.ERROR: |
| 31 |
print("Error during receive %s" % ws.exception()) |
| 32 |
elif msg.type == aiohttp.WSMsgType.CLOSED: |
| 33 |
pass |
| 34 |
|
| 35 |
break |
| 36 |
|
| 37 |
async with aiohttp.ClientSession() as session: |
| 38 |
async with session.ws_connect(url, autoclose=False, autoping=False) as ws: |
| 39 |
# send request |
| 40 |
dispatch_task = asyncio.create_task(dispatch(ws)) |
| 41 |
|
| 42 |
# Exit with Ctrl+D |
| 43 |
while line := await asyncio.to_thread(sys.stdin.readline): |
| 44 |
await ws.send_str(name + ": " + line) |
| 45 |
|
| 46 |
dispatch_task.cancel() |
| 47 |
with suppress(asyncio.CancelledError): |
| 48 |
await dispatch_task |
| 49 |
|
| 50 |
|
| 51 |
ARGS = argparse.ArgumentParser( |
| 52 |
description="websocket console client for wssrv.py example." |
| 53 |
) |
| 54 |
ARGS.add_argument( |
| 55 |
"--host", action="store", dest="host", default="127.0.0.1", help="Host name" |
| 56 |
) |
| 57 |
ARGS.add_argument( |
| 58 |
"--port", action="store", dest="port", default=8080, type=int, help="Port number" |
| 59 |
) |
| 60 |
|
| 61 |
if __name__ == "__main__": |
| 62 |
args = ARGS.parse_args() |
| 63 |
if ":" in args.host: |
| 64 |
args.host, port = args.host.split(":", 1) |
| 65 |
args.port = int(port) |
| 66 |
|
| 67 |
url = f"http://{args.host}:{args.port}" |
| 68 |
|
| 69 |
asyncio.run(start_client(url)) |