[Tutor] Unpickling data after passing over the network

Daniel Yoo dyoo at cs.wpi.edu
Sun Feb 11 19:48:52 CET 2007

> a socket.  Right now, I am pickling a basic string base 64 encoding and 
> sending the data over the network.  After the recipient client/server 
> receives the data, it is decoded and then unpickled.  The unpickling 
> fails with an EOFError, and I am not sure why.

Hi Adam,

Did you "flush" the output buffer?  Network sockets are, like files, 
typically buffered, so you may need to tell the system to not wait for the 
buffer to fill.

Let me look at your functions to see if there's anything else you'll want 
to think about.

> def SerialEncode(data):
>    import cPickle, base64
>    return base64.encodestring(cPickle.dumps(data,2))
> def DeserialDecode(data):
>    import cPickle, base64
>    return cPickle.loads(base64.decodestring(data))

You can simplify by pulling the imports of 'cPickle' and 'base64' out to 
the top.

>    mySocket.send( SerialEncode("Hello!"))

Ok, this is one source of a problem.

Remember what you did with the recv's earlier, with the looping?  Same 
thing: send() isn't guaranteed to write all the bytes out at once.  Read 
the documentation to send() a little closely, and you'll see the warning 


One way to get around this is to work at a higher level of abstraction: 
sockets can also be treated as file-like objects which do the looping for 
you automatically, at the expense of having less control over the socket. 
See socket.makefile():


Otherwise, everything else looks ok from a casual glance.

Good luck!

More information about the Tutor mailing list