下面的tcp客户机代码基本上是循环的,直到它能够与tcp服务器建立连接为止。在vs代码中调试时,我注意到每次调用create_connection()似乎都会创建一个新的ThreadPoolExecutor实例。当我的tcp服务器没有运行时,这可能会造成一个问题,因为似乎会创建无限数量的实例。当服务器不运行时,处理多次调用create_connection()的正确方法是什么?
async def do_tcp_connect(host, port, queue, shutdown_event, callbacks, connection_list):
logger = logging.getLogger('do_tcp_connect')
logger.debug('do_tcp_connect(): started')
while True:
try:
transport, protocol = await asyncio.get_running_loop().create_connection(lambda: asyncio_callback(host, port, queue, shutdown_event, callbacks, connection_list), host, port)
return
except (KeyboardInterrupt, SystemExit):
raise
except asyncio.CancelledError as ex:
logger.error("network_queue_consumer(): CancelledError: A asyncio coroutine task was cancelled, error={}".format(ex))
except AttributeError as ex:
logger.error("network_queue_consumer(): AttributeError: An attribute reference or assignment has failed, error:{}".format(ex))
except OSError as ex:
logger.error("network_queue_consumer(): OSError error:{}".format(ex))
except asyncio.TimeoutError:
continue
except Exception as ex:
logger.error('network_queue_consumer(): Exception occurred, error={}'.format(ex))
except:
logger.error("network_queue_consumer(): Unexpected error: {}".format(sys.exc_info()[0]))
raise
await asyncio.sleep(5.0)
logger.debug('do_tcp_connect(): completed')