Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 如何安全地关闭Trio中的连接?_Asynchronous_Connection_Python Trio - Fatal编程技术网

Asynchronous 如何安全地关闭Trio中的连接?

Asynchronous 如何安全地关闭Trio中的连接?,asynchronous,connection,python-trio,Asynchronous,Connection,Python Trio,我将连接的应用程序逻辑包装在一个大的try/except/finally块中: async def serve(self, stream: trio.SocketStream): try: async with trio.open_nursery() as nursery: pass # code goes here to do some reading and writing except Exception as e:

我将连接的应用程序逻辑包装在一个大的try/except/finally块中:

async def serve(self, stream: trio.SocketStream):
    try:
        async with trio.open_nursery() as nursery:
            pass  # code goes here to do some reading and writing 

    except Exception as e:
        print("Got exception:", e)
    except trio.Cancelled:
        print("Cancelled")
        raise
    # some other handlers, mostly just logging

    finally:
        # ... some other stuff ...
        # ... then shut the connection:
        with trio.move_on_after(1):
            await stream.aclose()
我不清楚是否应该在finally子句中尝试关闭连接。如果异常是由于应用程序错误引起的(来自连接的消息无效,或协同路由被取消),这似乎是正确的做法,但如果异常是连接从另一端关闭,那么这似乎适得其反-我希望旧异常会被新异常掩盖。有什么想法吗?我可以用自己的try/except来包装它,忽略任何例外情况。

,Joshua Oreman@oremanj善意地给出了这个答案:

Trio区分本地和远程关闭。如果远程端关闭了一个连接,那么仍然可以关闭它。(正是因为这个原因)

(如果它在本地获得了aclose()'d,那么再次使用aclose()也可以。无论哪种情况,它都是noop(除了执行检查点)

如果在关闭连接后使用连接(这是一个编程错误,您应该修复),则会出现
ClosedResourceError
,而如果在另一端出现问题后使用连接,则会出现
brokernResourceError
(由于网络的变幻莫测,有时可能会出现这种情况)