Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / examples / simpleclient.py
1
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
4
5
6 """
7 An example client. Run simpleserv.py first before running this.
8 """
9
10 from twisted.internet import reactor, protocol
11
12
13 # a client protocol
14
15 class EchoClient(protocol.Protocol):
16     """Once connected, send a message, then print the result."""
17     
18     def connectionMade(self):
19         self.transport.write("hello, world!")
20     
21     def dataReceived(self, data):
22         "As soon as any data is received, write it back."
23         print "Server said:", data
24         self.transport.loseConnection()
25     
26     def connectionLost(self, reason):
27         print "connection lost"
28
29 class EchoFactory(protocol.ClientFactory):
30     protocol = EchoClient
31
32     def clientConnectionFailed(self, connector, reason):
33         print "Connection failed - goodbye!"
34         reactor.stop()
35     
36     def clientConnectionLost(self, connector, reason):
37         print "Connection lost - goodbye!"
38         reactor.stop()
39
40
41 # this connects the protocol to a server runing on port 8000
42 def main():
43     f = EchoFactory()
44     reactor.connectTCP("localhost", 8000, f)
45     reactor.run()
46
47 # this only runs if the module was *not* imported
48 if __name__ == '__main__':
49     main()