diff --git a/telethon/network/connection/connection.py b/telethon/network/connection/connection.py index bbfc35c6..838b3b88 100644 --- a/telethon/network/connection/connection.py +++ b/telethon/network/connection/connection.py @@ -256,6 +256,8 @@ class Connection(abc.ABC): if not self._connected: return + self._connected = False + await helpers._cancel( self._log, send_task=self._send_task, @@ -279,8 +281,6 @@ class Connection(abc.ABC): # * ConnectionResetError self._log.info('%s during disconnect: %s', type(e), e) - self._connected = False - def send(self, data): """ Sends a packet of data through this connection mode. @@ -333,6 +333,8 @@ class Connection(abc.ABC): while self._connected: try: data = await self._recv() + except asyncio.CancelledError: + break except (IOError, asyncio.IncompleteReadError) as e: self._log.warning('Server closed the connection: %s', e) await self._recv_queue.put((None, e)) @@ -349,8 +351,6 @@ class Connection(abc.ABC): await self.disconnect() else: await self._recv_queue.put((data, None)) - except asyncio.CancelledError: - pass finally: await self.disconnect()