spacepaste

  1.  
  2. from __future__ import print_function
  3. from twisted.internet import reactor, protocol
  4. # a client protocol
  5. class EchoClient(protocol.Protocol):
  6. """Once connected, send a message, then print the result."""
  7. def connectionMade(self):
  8. self.transport.write("hello, world!")
  9. def dataReceived(self, data):
  10. "As soon as any data is received, write it back."
  11. print("Server said:", data)
  12. #self.transport.loseConnection()
  13. def connectionLost(self, reason):
  14. print("connection lost")
  15. class EchoFactory(protocol.ClientFactory):
  16. protocol = EchoClient
  17. def clientConnectionFailed(self, connector, reason):
  18. print("Connection failed - goodbye!")
  19. reactor.stop()
  20. def clientConnectionLost(self, connector, reason):
  21. print("Connection lost - goodbye!")
  22. reactor.stop()
  23. # this connects the protocol to a server running on port 8000
  24. def main():
  25. f = EchoFactory()
  26. reactor.connectTCP("localhost", 6000, f)
  27. reactor.run()
  28. # this only runs if the module was *not* imported
  29. if __name__ == '__main__':
  30. main()
  31.