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

Piet van Oostrum piet at cs.uu.nl
Sun Jul 19 08:55:20 CEST 2009


>>>>> John Machin <sjmachin at lexicon.net> (JM) wrote:

>JM> On Jul 19, 7:43 am, 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.

>JM> Apologies in advance for my ignorance -- the last time I dipped my toe
>JM> in that kind of water, protocols like zmodem and Kermit were all the
>JM> rage -- but I would have thought there would have been an off-the-
>JM> shelf library for peer-to-peer file transfer over a socket
>JM> interface ... not so?

Yes, many of them, for example HTTP or FTP. But I suppose they are
overkill in this situation. There are also remote procedure call
protocols which can do much more, like XMLRPC.

By the way if the image file
is the only thing you send, the client should close the socket after
sending and then the receiver will detect end of file which will be
detected by your `if len(data) == 0:'
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list