spacepaste

  1.  
  2. from twisted.internet.protocol import Factory
  3. from twisted.internet import reactor, protocol
  4. class QuoteProtocol(protocol.Protocol):
  5. def __init__(self, factory):
  6. self.factory = factory
  7. def connectionMade(self):
  8. self.factory.numConnections +=1
  9. def dataReceived(self, data):
  10. print(f"Number of connections received: %d" % (self.factory.numConnections,))
  11. print(f"> Received: ``%s''\n> Sending: ``%s''" % (data.decode('utf-8'), self.getQuote()))
  12. self.transport.write(self.getQuote())
  13. self.updateQuote(data)
  14. def connectionLost(self, reason):
  15. self.factory.numConnections -= 1
  16. def getQuote(self):
  17. return self.factory.quote
  18. def updateQuote(self, quote):
  19. self.factory.quote = quote
  20. class QuoteFactory(Factory):
  21. numConnections = 0
  22. def __init__(self, quote=None):
  23. self.quote = quote or "An apple a day keeps the doctor away"
  24. def buildProtocol(self, addr):
  25. return QuoteProtocol(self)
  26. reactor.listenTCP(10310, QuoteFactory())
  27. reactor.run()
  28.