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

MRAB python at mrabarnett.plus.com
Sat Jul 18 19:05:48 EDT 2009


twgray wrote:
> On Jul 18, 4:43 pm, Irmen de Jong <irmen.NOS... at xs4all.nl> wrote:
>> 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?  
>> You don't. Sockets are just endless streams of bytes. You will have to design some form
>> of 'wire protocol' that includes the length of the message that is to be read.
>> For instance a minimalistic protocol could be the following:
>> Send 4 bytes that contain the length (an int) then the data itself. The client reads 4
>> bytes, decodes it into the integer that tells it the length, and then reads the correct
>> amount of bytes from the socket.
>>
> Thanks for the reply.  But, now I have a newbie Python question.  If I
> send a 4 byte address from the embedded device, how do I convert that,
> in Python, to a 4 byte, or long, number?

If you send the length as 4 bytes then you'll have to decide whether
it's big-endian or little-endian. An alternative is to send the length
as characters, terminated by, say, '\n' or chr(0).



More information about the Python-list mailing list