1111import ssl
1212import sys
1313import urllib .parse
14+ from typing import NoReturn
1415
1516import trio
16- from trio_websocket import open_websocket_url , ConnectionClosed , HandshakeError
17+ from trio_websocket import (
18+ open_websocket_url ,
19+ ConnectionClosed ,
20+ HandshakeError ,
21+ WebSocketConnection ,
22+ CloseReason ,
23+ )
1724
1825
1926logging .basicConfig (level = logging .DEBUG )
2027here = pathlib .Path (__file__ ).parent
2128
2229
23- def commands ():
30+ def commands () -> None :
2431 ''' Print the supported commands. '''
2532 print ('Commands: ' )
2633 print ('send <MESSAGE> -> send message' )
@@ -29,7 +36,7 @@ def commands():
2936 print ()
3037
3138
32- def parse_args ():
39+ def parse_args () -> argparse . Namespace :
3340 ''' Parse command line arguments. '''
3441 parser = argparse .ArgumentParser (description = 'Example trio-websocket client' )
3542 parser .add_argument ('--heartbeat' , action = 'store_true' ,
@@ -38,7 +45,7 @@ def parse_args():
3845 return parser .parse_args ()
3946
4047
41- async def main (args ) :
48+ async def main (args : argparse . Namespace ) -> bool :
4249 ''' Main entry point, returning False in the case of logged error. '''
4350 if urllib .parse .urlsplit (args .url ).scheme == 'wss' :
4451 # Configure SSL context to handle our self-signed certificate. Most
@@ -59,9 +66,10 @@ async def main(args):
5966 except HandshakeError as e :
6067 logging .error ('Connection attempt failed: %s' , e )
6168 return False
69+ return True
6270
6371
64- async def handle_connection (ws , use_heartbeat ) :
72+ async def handle_connection (ws : WebSocketConnection , use_heartbeat : bool ) -> None :
6573 ''' Handle the connection. '''
6674 logging .debug ('Connected!' )
6775 try :
@@ -71,11 +79,12 @@ async def handle_connection(ws, use_heartbeat):
7179 nursery .start_soon (get_commands , ws )
7280 nursery .start_soon (get_messages , ws )
7381 except ConnectionClosed as cc :
82+ assert isinstance (cc .reason , CloseReason )
7483 reason = '<no reason>' if cc .reason .reason is None else f'"{ cc .reason .reason } "'
7584 print (f'Closed: { cc .reason .code } /{ cc .reason .name } { reason } ' )
7685
7786
78- async def heartbeat (ws , timeout , interval ) :
87+ async def heartbeat (ws : WebSocketConnection , timeout : float , interval : float ) -> NoReturn :
7988 '''
8089 Send periodic pings on WebSocket ``ws``.
8190
@@ -99,11 +108,10 @@ async def heartbeat(ws, timeout, interval):
99108 await trio .sleep (interval )
100109
101110
102- async def get_commands (ws ) :
111+ async def get_commands (ws : WebSocketConnection ) -> None :
103112 ''' In a loop: get a command from the user and execute it. '''
104113 while True :
105- cmd = await trio .to_thread .run_sync (input , 'cmd> ' ,
106- cancellable = True )
114+ cmd = await trio .to_thread .run_sync (input , 'cmd> ' )
107115 if cmd .startswith ('ping' ):
108116 payload = cmd [5 :].encode ('utf8' ) or None
109117 await ws .ping (payload )
@@ -123,11 +131,11 @@ async def get_commands(ws):
123131 await trio .sleep (0.25 )
124132
125133
126- async def get_messages (ws ) :
134+ async def get_messages (ws : WebSocketConnection ) -> None :
127135 ''' In a loop: get a WebSocket message and print it out. '''
128136 while True :
129137 message = await ws .get_message ()
130- print (f'message: { message } ' )
138+ print (f'message: { message !r } ' )
131139
132140
133141if __name__ == '__main__' :
0 commit comments