@@ -63,20 +63,34 @@ async def start(self):
6363 self .pre_start ()
6464
6565 while True :
66- connection = self .open_connection ()
67-
68- if not connection :
69- self .logger .error ('open connection failed' )
70- time .sleep (10 )
66+ try :
67+ connection = self .open_connection ()
68+
69+ if not connection :
70+ self .logger .error ('open connection failed' )
71+ time .sleep (10 )
72+ continue
73+ self .logger .info ('endpoint is %s' , connection )
74+
75+ uri = '%s?ticket=%s' % (connection ['endpoint' ], urllib .parse .quote_plus (connection ['ticket' ]))
76+ async with websockets .connect (uri ) as websocket :
77+ self .websocket = websocket
78+ async for raw_message in websocket :
79+ json_message = json .loads (raw_message )
80+ asyncio .create_task (self .background_task (json_message ))
81+ except KeyboardInterrupt as e :
82+ break
83+ except (asyncio .exceptions .CancelledError ,
84+ websockets .exceptions .ConnectionClosedError ) as e :
85+ self .logger .error ('[start] network exception, error=%s' , e )
86+ await asyncio .sleep (10 )
7187 continue
72- self .logger .info ('endpoint is %s' , connection )
73-
74- uri = '%s?ticket=%s' % (connection ['endpoint' ], urllib .parse .quote_plus (connection ['ticket' ]))
75- async with websockets .connect (uri ) as websocket :
76- self .websocket = websocket
77- async for raw_message in websocket :
78- json_message = json .loads (raw_message )
79- asyncio .create_task (self .background_task (json_message ))
88+ except Exception as e :
89+ await asyncio .sleep (3 )
90+ self .logger .exception ('unknown exception' , e )
91+ continue
92+ finally :
93+ pass
8094
8195 async def background_task (self , json_message ):
8296 try :
@@ -121,15 +135,8 @@ def start_forever(self):
121135 asyncio .run (self .start ())
122136 except KeyboardInterrupt as e :
123137 break
124- except (asyncio .exceptions .CancelledError ,
125- websockets .exceptions .ConnectionClosedError ) as e :
126- self .logger .error ('network exception, error=%s' , e )
127- time .sleep (10 )
128- continue
129- except Exception as e :
138+ finally :
130139 time .sleep (3 )
131- self .logger .exception ('unknown exception' , e )
132- continue
133140
134141 def open_connection (self ):
135142 self .logger .info ('open connection, url=%s' % DingTalkStreamClient .OPEN_CONNECTION_API )
0 commit comments