diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /third_party/python/aiohttp/examples/client_ws.py | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/python/aiohttp/examples/client_ws.py')
-rwxr-xr-x | third_party/python/aiohttp/examples/client_ws.py | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/third_party/python/aiohttp/examples/client_ws.py b/third_party/python/aiohttp/examples/client_ws.py new file mode 100755 index 0000000000..38d8300362 --- /dev/null +++ b/third_party/python/aiohttp/examples/client_ws.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""websocket cmd client for wssrv.py example.""" +import argparse +import asyncio +import signal +import sys + +import aiohttp + + +async def start_client(loop, url): + name = input("Please enter your name: ") + + # input reader + def stdin_callback(): + line = sys.stdin.buffer.readline().decode("utf-8") + if not line: + loop.stop() + else: + ws.send_str(name + ": " + line) + + loop.add_reader(sys.stdin.fileno(), stdin_callback) + + async def dispatch(): + while True: + msg = await ws.receive() + + if msg.type == aiohttp.WSMsgType.TEXT: + print("Text: ", msg.data.strip()) + elif msg.type == aiohttp.WSMsgType.BINARY: + print("Binary: ", msg.data) + elif msg.type == aiohttp.WSMsgType.PING: + ws.pong() + elif msg.type == aiohttp.WSMsgType.PONG: + print("Pong received") + else: + if msg.type == aiohttp.WSMsgType.CLOSE: + await ws.close() + elif msg.type == aiohttp.WSMsgType.ERROR: + print("Error during receive %s" % ws.exception()) + elif msg.type == aiohttp.WSMsgType.CLOSED: + pass + + break + + # send request + async with aiohttp.ClientSession() as session: + async with session.ws_connect(url, autoclose=False, autoping=False) as ws: + await dispatch() + + +ARGS = argparse.ArgumentParser( + description="websocket console client for wssrv.py example." +) +ARGS.add_argument( + "--host", action="store", dest="host", default="127.0.0.1", help="Host name" +) +ARGS.add_argument( + "--port", action="store", dest="port", default=8080, type=int, help="Port number" +) + +if __name__ == "__main__": + args = ARGS.parse_args() + if ":" in args.host: + args.host, port = args.host.split(":", 1) + args.port = int(port) + + url = f"http://{args.host}:{args.port}" + + loop = asyncio.get_event_loop() + + loop.add_signal_handler(signal.SIGINT, loop.stop) + loop.create_task(start_client(loop, url)) + loop.run_forever() |