Debian Codegraph @

docs/core/examples/echoclient.py

raw
1 #!/usr/bin/env python
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
4
5
6 from twisted.internet import task
7 from twisted.internet.defer import Deferred
8 from twisted.internet.protocol import ClientFactory
9 from twisted.protocols.basic import LineReceiver
10
11
12 class EchoClient(LineReceiver):
13 end = b"Bye-bye!"
14
15 def connectionMade(self):
16 self.sendLine(b"Hello, world!")
17 self.sendLine(b"What a fine day it is.")
18 self.sendLine(self.end)
19
20 def lineReceived(self, line):
21 print("receive:", line)
22 if line == self.end:
23 self.transport.loseConnection()
24
25
26 class EchoClientFactory(ClientFactory):
27 protocol = EchoClient
28
29 def __init__(self):
30 self.done = Deferred()
31
32 def clientConnectionFailed(self, connector, reason):
33 print("connection failed:", reason.getErrorMessage())
34 self.done.errback(reason)
35
36 def clientConnectionLost(self, connector, reason):
37 print("connection lost:", reason.getErrorMessage())
38 self.done.callback(None)
39
40
41 def main(reactor):
42 factory = EchoClientFactory()
43 reactor.connectTCP("localhost", 8000, factory)
44 return factory.done
45
46
47 if __name__ == "__main__":
48 task.react(main)