echo.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python
  2. from twisted.internet.protocol import Factory
  3. from twisted.internet.endpoints import TCP4ServerEndpoint
  4. from twisted.internet import reactor
  5. from twisted.internet.protocol import Protocol
  6. class QOTD(Protocol):
  7. def connectionMade(self):
  8. self.transport.write("An apple a day keeps the doctor away\r\n".encode("utf-8"))
  9. self.transport.loseConnection()
  10. class QOTDFactory(Factory):
  11. def buildProtocol(self, addr):
  12. return QOTD()
  13. # Why does this seem to be doing line buffering?
  14. # Because telnet defaults to line mode
  15. # ^]
  16. # telnet> mode character
  17. # or:
  18. # telnet> mode line
  19. # to toggle. (The echo works correctly, it's the telnet client that's silly.)
  20. class Echo(Protocol):
  21. def __init__(self, factory):
  22. self.factory = factory
  23. def connectionMade(self):
  24. self.factory.numProtocols = self.factory.numProtocols + 1
  25. self.transport.write(
  26. "Welome! There are currently {0} open connections.\n".format(
  27. self.factory.numProtocols ).encode('utf-8') )
  28. def connectionLost(self, reason):
  29. self.factory.numProtocols = self.factory.numProtocols - 1
  30. def dataReceived(self, data):
  31. self.transport.write(data)
  32. class EchoFactory(Factory):
  33. def __init__(self):
  34. self.numProtocols = 0
  35. def buildProtocol(self, addr):
  36. return Echo(self)
  37. endpoint = TCP4ServerEndpoint(reactor, 8007)
  38. endpoint.listen(EchoFactory())
  39. qotdpoint = TCP4ServerEndpoint(reactor, 8008)
  40. qotdpoint.listen(QOTDFactory())
  41. reactor.run()