Python blocking recv returns less data than asked for

半腔热情 提交于 2021-01-28 22:07:21

问题


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?


回答1:


The length you give to recv is a maximum, not a target. There's no guarantee that recv will wait for Len 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.



来源:https://stackoverflow.com/questions/7438013/python-blocking-recv-returns-less-data-than-asked-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!