Python阻塞recv返回的数据少于要求的数据
我有一个 C 语言的 echo 服务器和一个 Python 语言的测试客户端。服务器的读取缓冲区有限,例如 16 字节。当客户端发送超过16个字节时,它会先读取16个字节,写回到客户端,然后再读取。
我使用 telnet
测试了服务器,并得到了与输入相同的字符串,即使它的长度超过 16 个字节。然而这个Python客户端不起作用。
//data is initialized to be 20 bytes data
Len = 20
sock.setblocking(1)
sock.send(data)
recvdata = sock.recv(Len)
if(recvdata != data):
print recvdata.encode('hex')
print Len
print data.encode('hex')
该客户端仅接收服务器写回的前 16 个字节。服务器日志确实显示两次写入 (16 + 4)。 Python 输出看起来像这样,
1234567890123456 //recvdata
20
12345678901234567890 //sent data
我不确定为什么会发生这种情况,为什么阻塞 recv()
返回的数据少于要求的数据?
I have an echo server in C and a test client in Python. The server has a limited read buffer, eg 16bytes. When a client send more than 16 bytes, it will first read 16, write back to client and then read again.
I tested the server with telnet
, and I got back the same string as my input, even it's longer than 16 bytes. However this Python client does not work.
//data is initialized to be 20 bytes data
Len = 20
sock.setblocking(1)
sock.send(data)
recvdata = sock.recv(Len)
if(recvdata != data):
print recvdata.encode('hex')
print Len
print data.encode('hex')
This client only receive the first 16 bytes that server writes back. The server log does show two writes (16 + 4). Python output looks like this
1234567890123456 //recvdata
20
12345678901234567890 //sent data
I'm not sure why this is happening, How come a blocking recv()
returns less data than it is asked for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您给
recv
的长度是最大值,而不是目标。无法保证recv
会等待接收Len
字节 - 它可以在读取任何数据后立即返回。recv
的手册页说:接收调用通常会返回任何可用数据,最多可达请求的数量,而不是等待收到请求的全部数量。如果您需要要读取给定数量的字节,您需要在循环中调用
recv
并连接返回的数据包,直到读取足够的数据为止。The length you give to
recv
is a maximum, not a target. There's no guarantee thatrecv
will wait forLen
bytes to be received - it can return as soon as it's read any data at all.The man page for
recv
says: The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.If you need to read a given number of bytes, you need to call
recv
in a loop and concatenate the returned packets until you have read enough.