Only reconnect from background thread if .disconnect wasn't called

This commit is contained in:
Lonami Exo 2017-09-03 13:44:52 +02:00
parent 626778bd32
commit 27408b46da

View File

@ -155,12 +155,15 @@ class TelegramClient(TelegramBareClient):
if not self._sender or not self._sender.is_connected(): if not self._sender or not self._sender.is_connected():
return return
super().disconnect()
# The existing thread will close eventually, since it's # The existing thread will close eventually, since it's
# only running while the MtProtoSender.is_connected() # only running while the MtProtoSender.is_connected()
self._recv_thread = None self._recv_thread = None
# This will trigger a "ConnectionResetError", usually, the background
# thread would try restarting the connection but since the
# ._recv_thread = None, it knows it doesn't have to.
super().disconnect()
# Also disconnect all the cached senders # Also disconnect all the cached senders
for sender in self._cached_clients.values(): for sender in self._cached_clients.values():
sender.disconnect() sender.disconnect()
@ -213,8 +216,8 @@ class TelegramClient(TelegramBareClient):
except (PhoneMigrateError, NetworkMigrateError, UserMigrateError) as e: except (PhoneMigrateError, NetworkMigrateError, UserMigrateError) as e:
self._logger.debug('DC error when invoking request, ' self._logger.debug('DC error when invoking request, '
'attempting to reconnect at DC {}' 'attempting to reconnect at DC {}'
.format(e.new_dc)) .format(e.new_dc))
self.reconnect(new_dc=e.new_dc) self.reconnect(new_dc=e.new_dc)
return self.invoke(request) return self.invoke(request)
@ -911,14 +914,17 @@ class TelegramClient(TelegramBareClient):
# #
# This way, sending and receiving will be completely independent. # This way, sending and receiving will be completely independent.
def _recv_thread_impl(self): def _recv_thread_impl(self):
while self._sender.is_connected(): while self._sender and self._sender.is_connected():
try: try:
self._sender.receive() self._sender.receive()
except TimeoutError: except TimeoutError:
# No problem. # No problem.
pass pass
except ConnectionResetError: except ConnectionResetError:
self._logger.debug('Server disconnected us. Reconnecting...') if self._recv_thread is not None:
self.reconnect() # Do NOT attempt reconnecting unless the connection was
# finished by the user -> ._recv_thread is None
self._logger.debug('Server disconnected us. Reconnecting...')
self.reconnect()
# endregion # endregion