diff --git a/telethon/extensions/tcp_client.py b/telethon/extensions/tcp_client.py index 9a37c685..8453af5e 100644 --- a/telethon/extensions/tcp_client.py +++ b/telethon/extensions/tcp_client.py @@ -3,12 +3,15 @@ import errno import socket from datetime import timedelta from io import BytesIO, BufferedWriter +from threading import Lock class TcpClient: def __init__(self, proxy=None, timeout=timedelta(seconds=5)): self._proxy = proxy self._socket = None + self._closing_lock = Lock() + if isinstance(timeout, timedelta): self._timeout = timeout.seconds elif isinstance(timeout, int) or isinstance(timeout, float): @@ -48,14 +51,19 @@ class TcpClient: def close(self): """Closes the connection""" - try: - if self.connected: - self._socket.shutdown(socket.SHUT_RDWR) - self._socket.close() - except OSError: - pass # Ignore ENOTCONN, EBADF, and any other error when closing - finally: - self._socket = None + if self._closing_lock.locked(): + # Already closing, no need to close again (avoid None.close()) + return + + with self._closing_lock: + try: + if self._socket is not None: + self._socket.shutdown(socket.SHUT_RDWR) + self._socket.close() + except OSError: + pass # Ignore ENOTCONN, EBADF, and any other error when closing + finally: + self._socket = None def write(self, data): """Writes (sends) the specified bytes to the connected peer"""