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?
The length you give to
recvis a maximum, not a target. There’s no guarantee thatrecvwill wait forLenbytes to be received – it can return as soon as it’s read any data at all.The man page for
recvsays: 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
recvin a loop and concatenate the returned packets until you have read enough.