MCPcopy Create free account
hub / github.com/actix/examples / start_client

Function start_client

websockets/chat/client.py:12–51  ·  view source on GitHub ↗
(url: str)

Source from the content-addressed store, hash-verified

10
11
12async 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 if line.startswith("/"):
45 await ws.send_str(line)
46 else:
47 await ws.send_str(name + ": " + line)
48
49 dispatch_task.cancel()
50 with suppress(asyncio.CancelledError):
51 await dispatch_task
52
53
54ARGS = argparse.ArgumentParser(

Callers 1

client.pyFile · 0.70

Calls 1

dispatchFunction · 0.70

Tested by

no test coverage detected