How to receive a data file of unknown length using a python socket?

MRAB python at mrabarnett.plus.com
Sat Jul 18 20:33:32 EDT 2009


Nobody wrote:
> On Sat, 18 Jul 2009 14:33:48 -0700, twgray wrote:
> 
>> It appears to be locking up in  'data=self.s.recv(MAXPACKETLEN)' on
>> the final packet, which will always be less than MAXPACKETLEN.
>>
>> I guess my question is, how do I detect end of data on the client side?
> 
> recv() should return zero when the sender closes its end of the connection.
> 
> Is the sender actually closing its end? If you are unsure, use a packet
> sniffer such as tcpdump to look for a packet with the FIN flag.
> 
> If you need to keep the connection open for further transfers, you need to
> incorporate some mechanism for identifying the end of the data into the
> protocol. As others have suggested, prefixing the data by its length is
> one option. Another is to use an end-of-data marker, but then you need a
> mechanism to "escape" the marker if it occurs in the data. A length prefix
> is probably simpler to implement, but has the disadvantage that you can't
> start sending the data until you know how long it is going to be.
> 
You could send it in chunks, ending with a chunk length of zero.



More information about the Python-list mailing list