Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / howto / listings / pb / pbAnonClient.py
1 #!/usr/bin/env python
2
3 # Copyright (c) Twisted Matrix Laboratories.
4 # See LICENSE for details.
5
6 """
7 Client which will talk to the server run by pbAnonServer.py, logging in
8 either anonymously or with username/password credentials.
9 """
10
11 from sys import stdout
12
13 from twisted.python.log import err, startLogging
14 from twisted.cred.credentials import Anonymous, UsernamePassword
15 from twisted.internet import reactor
16 from twisted.internet.defer import gatherResults
17 from twisted.spread.pb import PBClientFactory
18
19
20 def error(why, msg):
21     """
22     Catch-all errback which simply logs the failure.  This isn't expected to
23     be invoked in the normal case for this example.
24     """
25     err(why, msg)
26
27
28 def connected(perspective):
29     """
30     Login callback which invokes the remote "foo" method on the perspective
31     which the server returned.
32     """
33     print "got perspective1 ref:", perspective
34     print "asking it to foo(13)"
35     return perspective.callRemote("foo", 13)
36
37
38 def finished(ignored):
39     """
40     Callback invoked when both logins and method calls have finished to shut
41     down the reactor so the example exits.
42     """
43     reactor.stop()
44
45
46 def main():
47     """
48     Connect to a PB server running on port 8800 on localhost and log in to
49     it, both anonymously and using a username/password it will recognize.
50     """
51     startLogging(stdout)
52     factory = PBClientFactory()
53     reactor.connectTCP("localhost", 8800, factory)
54
55     anonymousLogin = factory.login(Anonymous())
56     anonymousLogin.addCallback(connected)
57     anonymousLogin.addErrback(error, "Anonymous login failed")
58
59     usernameLogin = factory.login(UsernamePassword("user1", "pass1"))
60     usernameLogin.addCallback(connected)
61     usernameLogin.addErrback(error, "Username/password login failed")
62
63     bothDeferreds = gatherResults([anonymousLogin, usernameLogin])
64     bothDeferreds.addCallback(finished)
65
66     reactor.run()
67
68
69 if __name__ == '__main__':
70     main()