Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / howto / listings / pb / pb4client.py
1 #!/usr/bin/env python
2
3 # Copyright (c) Twisted Matrix Laboratories.
4 # See LICENSE for details.
5
6 from twisted.spread import pb
7 from twisted.internet import reactor
8
9 def main():
10     rootobj_def = pb.getObjectAt("localhost", 8800, 30)
11     rootobj_def.addCallbacks(got_rootobj)
12     obj2_def = getSomeObjectAt("localhost", 8800, 30, "two")
13     obj2_def.addCallbacks(got_obj2)
14     obj3_def = getSomeObjectAt("localhost", 8800, 30, "three")
15     obj3_def.addCallbacks(got_obj3)
16     reactor.run()
17
18 def got_rootobj(rootobj):
19     print "got root object:", rootobj
20     print "telling root object to do foo(A)"
21     rootobj.callRemote("foo", "A")
22
23 def got_obj2(obj2):
24     print "got second object:", obj2
25     print "telling second object to do foo(B)"
26     obj2.callRemote("foo", "B")
27
28 def got_obj3(obj3):
29     print "got third object:", obj3
30     print "telling third object to do foo(C)"
31     obj3.callRemote("foo", "C")
32
33 class my_ObjectRetrieval(pb._ObjectRetrieval):
34     def __init__(self, broker, d, objname):
35         pb._ObjectRetrieval.__init__(self, broker, d)
36         self.objname = objname
37     def connectionMade(self):
38         assert not self.term, "How did this get called?"
39         x = self.broker.remoteForName(self.objname)
40         del self.broker
41         self.term = 1
42         self.deferred.callback(x)
43         
44 def getSomeObjectAt(host, port, timeout=None, objname="root"):
45     from twisted.internet import defer
46     from twisted.spread.pb import Broker, BrokerClientFactory
47     d = defer.Deferred()
48     b = Broker(1)
49     bf = BrokerClientFactory(b)
50     my_ObjectRetrieval(b, d, objname)
51     if host == "unix":
52         # every time you use this, God kills a kitten
53         reactor.connectUNIX(port, bf, timeout)
54     else:
55         reactor.connectTCP(host, port, bf, timeout)
56     return d
57
58 main()