Python asyncio中loop.sock_recv是否会抛出异常?
我在用Python asyncio做Socket编程时写了这段代码:
buff = b"" try: while len(buff) < 100: # 原代码此处多了一个多余的右括号,需修正 buff += await loop.sock_recv(srv_sock, 4096) except Exception as exp: raise exp
但不确定loop.sock_recv会不会抛出异常。查官方文档时发现,这个API的描述里没提异常:
Receive up to nbytes from sock. Asynchronous version of socket.recv().
Return the received data as a bytes object.
sock must be a non-blocking socket.
而loop.sock_sendall的文档则明确说明出错会抛异常:
This method continues to send to the socket until either all data in data has been sent or an error occurs. None is returned on success. On error, an exception is raised. Additionally, there is no way to determine how much data, if any, was successfully processed by the receiving end of the connection.
结论:loop.sock_recv确实会抛出异常
作为同步socket.recv()的异步版本,它的异常行为和同步方法完全一致,常见的异常场景包括:
- 连接被对等方重置时,抛出
ConnectionResetError - 传入阻塞socket等无效参数时,抛出
OSError子类异常 - 其他socket级错误(如地址无效、权限不足等)也会对应抛出
OSError的子类
官方文档没单独标注异常,是因为它复用了同步socket方法的异常定义,你可以参考同步socket.recv()的文档确认所有可能的异常类型。另外需要注意:当连接被正常关闭时,loop.sock_recv会返回空bytes对象,这不属于异常,但需要在代码中处理,避免无限循环。
内容的提问来源于stack exchange,提问作者NPE

