Send a Class Object by Socket

brueckd at tbye.com brueckd at tbye.com
Mon Jan 7 14:28:41 EST 2002


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





More information about the Python-list mailing list