Send a Class Object by Socket

Hugo Martires hugomartires at hotmail.com
Tue Jan 8 17:44:34 CET 2002


<brueckd at tbye.com> wrote in message news:<mailman.1010432830.27713.python-list at python.org>...
> On 7 Jan 2002, Hugo Martires wrote:
> 
> > I wan't to send an object of my class vector() to a client socket.
> > When the client receive the object, i wan't to treat it with all the
> > class functions of that object. (They exist on the remote computer)
> >
> > My problem is:
> > 	When the object reach the client, how can the client recognize it
> > like an object of the class vector ?
> 
> Hi Hugo,
> 
> If both sides of the connection have a copy of the class definition, then
> you can often just pickle the object and send it as a string. For example,
> assuming you have a module 'm' that defines a class 'Foo' then you can try
> something like this:
> 
> ---- (module m) ----
> class Foo:
>   def __init__(self, a, b):
>     self.a, self.b = a,b
> 
> ---- (server side) ----
> import m, socket, cPickle
> 
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind(('',6666))
> s.listen(1)
> q,v = s.accept()
> foo = cPickle.loads(q.recv(4096))
> print foo.a, foo.b
> 
> ---- (client side) ----
> import m, socket, cPickle
> 
> foo = m.Foo(1,'Hello!')
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect(('', 6666)
> s.send(cPickle.dumps(foo, 1))
> 
> 
> -Dave

This is my class vector:

class vector:
    def __init__(self,s):
        self.vet=array('f')
        self.size=s
        for i in range(self.size):
          self.vet.append(0.5)



My server is trying to send an array to the client.
  vp_master=vector(6)
  CliSock.send(cPickle.dumps(vp_master) )

That's how my client receive data:
 data = cPickle.loads(  CliSock.recv(BUFSIZ) )

But the server give's me this error:

 File "./serv2.py", line 41, in ?
    CliSock.send(cPickle.dumps(vp_master) )
cPickle.PicklingError: Cannot pickle <type 'array'> objects.

Do you know ho to picke an array ?
Tanks



More information about the Python-list mailing list