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

sandyethadka at gmail.com sandyethadka at gmail.com
Wed Apr 22 18:26:11 CEST 2015


On Sunday, 19 July 2009 03:03:48 UTC+5:30, twgray  wrote:
> I am attempting to send a jpeg image file created on an embedded
> device over a wifi socket to a Python client running on a Linux pc
> (Ubuntu).  All works well, except I don't know, on the pc client side,
> what the file size is?  The following is a snippet:
> 
> [code]
>         f = open("frame.jpg",mode = 'wb')
>        while True:
>             data = self.s.recv(MAXPACKETLEN)
>             if len(data) == 0:
>                 break
>             recvd += len(data)
>             f.write(data)
>         f.close()
> [end]
> 
> 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?



One way would be to send file size at the beginning. Like you can make first s.send(size) to only contain size in string converted mode by padding the integer size value to be equal to BufferSize. You can maybe use .rjust() method of string for this purpose. Then use this data to set the no of times you gotta do s.recv(BufferSize) in receiving end....Hope this helps.



More information about the Python-list mailing list