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