我尝试在以下 python 代码中使用标志“MSG_DONTWAIT
”:
RECV_BUFFER_SIZE = 1024
buff = memoryview(bytearray(RECV_BUFFER_SIZE))
x = client_socket.recv_into(buff, RECV_BUFFER_SIZE, socket.MSG_DONTWAIT)
我只是从套接字读取数据。
奇怪的是,当我使用“MSG_WAITALL”标志时,代码工作正常,但失败并出现以下错误:
x = client_socket.recv_into(buff, RECV_BUFFER_SIZE, socket.MSG_DONTWAIT)
AttributeError: module 'socket' has no attribute 'MSG_DONTWAIT'
当我尝试使用存在 'MSG_WAITALL'
的同一类 MsgFlag 中的 'MSG_DONTWAIT'
时。我在 Windows 平台上运行这个。
最佳答案
您收到错误是因为 Windows 的 Python 套接字模块中未定义 MSG_DONTWAIT
。 Python 只充当底层套接字系统的一个微小包装器,它是 Windows 上的 Winsock2。特别是 MSG_DONTWAIT
似乎不是由 Posix 定义的,也不存在于 Winsock 中。在 Unix 或 BSD 系统上,它将在 Python socket
模块中定义,我刚刚在 FreeBSD 10 系统上进行了控制。
根据this other SO question ,并阅读相关的post后,我认为你必须在 Windows 上明确地将套接字置于非阻塞模式:
RECV_BUFFER_SIZE = 1024
buff = memoryview(bytearray(RECV_BUFFER_SIZE))
client_socket.setblocking(0) # put socket in non blocking mode
try: # a BlockingIOError is raised if nothing is available
x = client_socket.recv_into(buff, RECV_BUFFER_SIZE, 0)
except BlockingIOError:
x = 0
关于python - 属性错误: module 'socket' has no attribute 'MSG_DONTWAIT' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54071217/