From 673660242422fb4b852e84dd028af6a2a50002cb Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Sat, 23 Jul 2022 22:52:21 +0200 Subject: [PATCH] Handle socket.connect() blocking-ness --- pyrogram/connection/transport/tcp/tcp.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pyrogram/connection/transport/tcp/tcp.py b/pyrogram/connection/transport/tcp/tcp.py index 5cd67937..c0efb625 100644 --- a/pyrogram/connection/transport/tcp/tcp.py +++ b/pyrogram/connection/transport/tcp/tcp.py @@ -21,6 +21,7 @@ import ipaddress import logging import socket import time +from concurrent.futures import ThreadPoolExecutor try: import socks @@ -78,7 +79,11 @@ class TCP: self.socket.settimeout(TCP.TIMEOUT) async def connect(self, address: tuple): - self.socket.connect(address) + # The socket used by the whole logic is blocking and thus it blocks when connecting. + # Offload the task to a thread executor to avoid blocking the main event loop. + with ThreadPoolExecutor(1) as executor: + await self.loop.run_in_executor(executor, self.socket.connect, address) + self.reader, self.writer = await asyncio.open_connection(sock=self.socket) def close(self):