1
0
mirror of https://github.com/actix/examples synced 2024-11-24 06:43:00 +01:00
examples/websockets/chat/client.py

77 lines
2.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
2022-12-11 12:30:31 +01:00
"""websocket cmd client for web_ws.py example."""
import argparse
import asyncio
import sys
2022-12-11 12:30:31 +01:00
from contextlib import suppress
import aiohttp
2022-12-11 12:30:31 +01:00
async def start_client(url: str) -> None:
name = input("Please enter your name: ")
2022-12-11 12:30:31 +01:00
async def dispatch(ws: aiohttp.ClientWebSocketResponse) -> None:
2018-12-31 07:28:42 +01:00
while True:
msg = await ws.receive()
2022-12-11 12:30:31 +01:00
if msg.type == aiohttp.WSMsgType.TEXT:
2022-12-11 12:30:31 +01:00
print("Text: ", msg.data.strip())
elif msg.type == aiohttp.WSMsgType.BINARY:
2022-12-11 12:30:31 +01:00
print("Binary: ", msg.data)
elif msg.type == aiohttp.WSMsgType.PING:
2018-12-31 07:28:42 +01:00
await ws.pong()
elif msg.type == aiohttp.WSMsgType.PONG:
2022-12-11 12:30:31 +01:00
print("Pong received")
else:
if msg.type == aiohttp.WSMsgType.CLOSE:
2018-12-31 07:28:42 +01:00
await ws.close()
elif msg.type == aiohttp.WSMsgType.ERROR:
2022-12-11 12:30:31 +01:00
print("Error during receive %s" % ws.exception())
elif msg.type == aiohttp.WSMsgType.CLOSED:
pass
2018-12-31 07:28:42 +01:00
2022-12-11 12:30:31 +01:00
break
2018-12-31 07:28:42 +01:00
2022-12-11 12:30:31 +01:00
async with aiohttp.ClientSession() as session:
async with session.ws_connect(url, autoclose=False, autoping=False) as ws:
# send request
dispatch_task = asyncio.create_task(dispatch(ws))
2018-12-31 07:28:42 +01:00
2022-12-11 12:30:31 +01:00
# Exit with Ctrl+D
while line := await asyncio.to_thread(sys.stdin.readline):
await ws.send_str(name + ": " + line)
2018-12-31 07:28:42 +01:00
2022-12-11 12:30:31 +01:00
dispatch_task.cancel()
with suppress(asyncio.CancelledError):
await dispatch_task
ARGS = argparse.ArgumentParser(
2022-12-11 12:30:31 +01:00
description="websocket console client for wssrv.py example."
)
ARGS.add_argument(
2022-12-11 12:30:31 +01:00
"--host", action="store", dest="host", default="127.0.0.1", help="Host name"
)
ARGS.add_argument(
2022-12-11 12:30:31 +01:00
"--port", action="store", dest="port", default=8080, type=int, help="Port number"
)
2022-12-11 12:30:31 +01:00
if __name__ == "__main__":
args = ARGS.parse_args()
2022-12-11 12:30:31 +01:00
if ":" in args.host:
args.host, port = args.host.split(":", 1)
args.port = int(port)
2022-12-11 12:30:31 +01:00
url = f"http://{args.host}:{args.port}/ws"
2022-12-11 12:30:31 +01:00
print("""
/list list all available rooms
/join name join room, if room does not exist, create new one
/name name set session name
some message just string, send message to all peers in same room
ctrl-D to exit
""")
asyncio.run(start_client(url))