Read / Write image file

Peter Hansen peter at engcorp.com
Wed May 4 08:32:48 EDT 2005


codecraig wrote:
> so something like,
> 
> x = sock.recv(1024)
> while (len(x) > 0):
>     # do stuff
>     x = sock.recv(1024)
> 
> 
> ??
> 
> So what if the client sends 4 bytes, and then sends 8000 bytes?  WIll I
> get the first 4 bytes as a separate msg so to speak?  Basically i want
> to catch each message from the client as a whole.

You cannot guarante *anything* except that (I believe) you will not 
receive zero bytes from .recv() as long as the socket is open.

Those four bytes the client sends: technically they could come as any 
combination, including four separate one-byte packets (though that is at 
least highly unlikely, if not actually impossible in practice).  The 
8000 bytes?  Some of them could actually arrive with the four bytes, and 
they could also be split into many smaller packets, with you having 
absolutely no say in the matter, and no way to control it.

Don't fight the way TCP works: learn to use it the way everyone else 
does, or better yet: don't reinvent the wheel.  Use an existing package 
that already does all the low-level stuff that you are trying to do and 
which does it reliably.  Twisted, some of the standard library options, 
or something else.  At the very least, look at some existing code to see 
how complex it has to be to work reliably, or look at a book like the 
Nutshell book to learn to do it properly.

-Peter



More information about the Python-list mailing list