Handle proxy socket connections using thread executors

This commit is contained in:
Dan 2022-12-28 00:14:04 +01:00
parent 1fa6f3b924
commit 2dca5aeac2

View File

@ -20,6 +20,7 @@ import asyncio
import ipaddress import ipaddress
import logging import logging
import socket import socket
from concurrent.futures import ThreadPoolExecutor
import socks import socks
@ -38,6 +39,8 @@ class TCP:
self.lock = asyncio.Lock() self.lock = asyncio.Lock()
self.loop = asyncio.get_event_loop() self.loop = asyncio.get_event_loop()
self.proxy = proxy
if proxy: if proxy:
hostname = proxy.get("hostname") hostname = proxy.get("hostname")
@ -71,6 +74,10 @@ class TCP:
self.socket.setblocking(False) self.socket.setblocking(False)
async def connect(self, address: tuple): async def connect(self, address: tuple):
if self.proxy:
with ThreadPoolExecutor(1) as executor:
await self.loop.run_in_executor(executor, self.socket.connect, address)
else:
try: try:
await asyncio.wait_for(asyncio.get_event_loop().sock_connect(self.socket, address), TCP.TIMEOUT) await asyncio.wait_for(asyncio.get_event_loop().sock_connect(self.socket, address), TCP.TIMEOUT)
except asyncio.TimeoutError: # Re-raise as TimeoutError. asyncio.TimeoutError is deprecated in 3.11 except asyncio.TimeoutError: # Re-raise as TimeoutError. asyncio.TimeoutError is deprecated in 3.11