twisted_basic_server.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env python3
  2. # pg 665 of Learning Python Networking
  3. from twisted.internet import reactor
  4. from twisted.internet.protocol import Protocol, Factory
  5. class MessageLogger(Protocol):
  6. def connectionMade(self):
  7. print('Client connection from:', self.transport.client)
  8. def connectionLost(self, reason):
  9. print('Client disconnected from:', self.transport.client)
  10. def dataReceived(self, data):
  11. self.transport.write(data)
  12. print("Message sent by the client: ", data.decode("utf-8"))
  13. class MessageFactory(Factory):
  14. def buildProtocol(self, addr):
  15. print("building MessageLogger for:", addr)
  16. return MessageLogger()
  17. # I don't see these methods EVER being called?!
  18. def clientConnectionFailed(self, connector, reason):
  19. print ("Connection failed")
  20. reactor.stop()
  21. def clientConnectionLost(self, connector, reason):
  22. print ("Connection lost")
  23. reactor.stop()
  24. #this connects the protocol to a server running on port 8080
  25. if __name__ == '__main__':
  26. factory = Factory()
  27. factory.protocol = MessageLogger
  28. reactor.listenTCP(8081, factory)
  29. # Using MessageFactory class, I can print information on "buildProtocol" call.
  30. reactor.listenTCP(8080, MessageFactory())
  31. reactor.run()