echoserver.py
from twisted.internet.protocol import Protocol, ServerFactory from twisted.internet import reactor __author__ = 'xueleng' class Echo(Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(ServerFactory): def buildProtocol(self, addr): return Echo(); reactor.listenTCP(8000, EchoFactory()) reactor.run()
from twisted.internet.protocol import Protocol, ClientFactory from twisted.internet import reactor __author__ = 'xueleng' class EchoClient(Protocol): def connectionMade(self): self.transport.write('Hello, World!') def dataReceived(self, data): print 'Server said: %s' % data self.transport.loseConnection() class EchoFactory(ClientFactory): def buildProtocol(self, addr): return EchoClient() def clientConnectionFailed(self, connector, reason): print 'Connection failed' reactor.stop() def clientConnectionLost(self, connector, reason): print 'Connection lose' reactor.stop() reactor.connectTCP('localhost', 8000, EchoFactory()) reactor.run()