您的问题“从套接字读取:是否保证至少获得 x 个字节?”的简单答案是no。查看这些套接字方法的文档字符串:
>>> import socket
>>> s = socket.socket()
>>> print s.recv.__doc__
recv(buffersize[, flags]) -> data
Receive up to buffersize bytes from the socket. For the optional flags
argument, see the Unix manual. When no data is available, block until
at least one byte is available or until the remote end is closed. When
the remote end is closed and all data is read, return the empty string.
>>>
>>> print s.settimeout.__doc__
settimeout(timeout)
Set a timeout on socket operations. 'timeout' can be a float,
giving in seconds, or None. Setting a timeout of None disables
the timeout feature and is equivalent to setblocking(1).
Setting a timeout of zero is the same as setblocking(0).
>>>
>>> print s.setblocking.__doc__
setblocking(flag)
Set the socket to blocking (flag is true) or non-blocking (false).
setblocking(True) is equivalent to settimeout(None);
setblocking(False) is equivalent to settimeout(0.0).
从中可以清楚地看出,recv()
不需要返回您要求的那么多字节。此外,由于您正在调用settimeout(10.0)
,因此可能会在recv()
. 在这种情况下,recv()
将返回它已读取的内容 - 这将比您要求的要少(但一致 < 4 字节似乎不太可能)。
您datagram
在问题中提到这意味着您正在使用(无连接)UDP 套接字(不是 TCP)。此处描述了区别。发布的代码没有显示套接字创建,所以我们只能在这里猜测,但是,这个细节可能很重要。如果您可以发布更完整的代码示例,这可能会有所帮助。
如果问题是可重现的,您可以禁用超时(顺便说一句,您似乎没有处理)并查看是否可以解决问题。