如何为连接到服务器的函数实现自定义超时

问题描述

我想使用 Python API 为 coppelia Sim 建立与 b0 客户端的连接。不幸的是,这个连接函数没有超时,如果连接失败就会无限期运行。

为了解决这个问题,我尝试将连接移动到一个单独的进程(多处理)并在几秒钟后检查该进程是否还活着。如果仍然是,我终止进程并继续执行程序。

这种工作,因为它不再阻塞我的程序,但是当连接成功时进程不会停止,所以它会终止进程,即使连接成功。

如何解决此问题并将 b0client 写入全局变量

def connection_function():
    global b0client
    b0client = b0remoteapi.remoteapiClient('b0remoteapi_pythonClient','b0remoteapi',60)
    print('Success!')
    return 0


def establish_b0_connection(timeout):
    connection_process = multiprocessing.Process(target=connection_function)
    connection_process.start()

    # Wait for [timeout] seconds or until process finishes
    connection_process.join(timeout=timeout)

    # If thread is still active
    if connection_process.is_alive():
        print('[INITIALIZATION OF B0 API CLIENT Failed]')

        # Terminate - may not work if process is stuck for good
        connection_process.terminate()

        # OR Kill - will work for sure,no chance for process to finish nicely however
        # connection_process.kill()

        connection_process.join()
        print('[CONTINUING WITHOUT B0 API CLIENT]')
        return False
    else:
        return True

if __name__ == '__main__':
    b0client = None
    establish_b0_connection(timeout=5)
    # Continue with the code,with or without connection.
    # ...

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)