Reading socket binary data?

Michael Simpson msimpson at hotmail.com
Thu Feb 27 22:02:15 EST 2003


Sweet...

Thanks,
Michael

"Jeremy Hylton" <jeremy at zope.com> wrote in message
news:mailman.1046397806.6843.python-list at python.org...
> > In C:
> >
> > struct FOO
> > {
> > short a;
> > char b;
> > long c;
> > }
> >
> > I can read something into a data object using the sizeof(FOO)
> >
> > i.e. recv(socket, buffer, sizeof(FOO),....
> >
> > In Python, I get
> >
> > data = socket.recv(1024)
> >
> > How to I translate data to a struct FOO type or a series of objects that
> > represent those fields?
>
> The struct module does this sort of work.
> http://www.python.org/doc/current/lib/module-struct.html
>
> I find it helpful to use a class method as a factory for classes that are
> designed to be serialized using struct.  The fromString() method on class
> Foo will create Foo instances from a string.  It keeps the constructor
> simple.
>
> class Foo:
>     def __init__(self, a, b, c):
>         self.a = a
>         self.b = b
>         self.c = c
>
>     _fmt = "hcl"
>
>     def fromString(cls, s):
>         return cls(*struct.unpack(cls._fmt, s))
>
>     fromString = classmethod(fromString)
>
>     def toString(self):
>         return struct.pack(cls._fmt, self.a, self.b, self.c)
>
> Jeremy
>
>






More information about the Python-list mailing list