Guest User

Untitled

a guest
Jan 3rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. from twisted.internet import reactor, protocol
  2.  
  3.  
  4. class QuoteProtocol(protocol.Protocol):
  5. def __init__(self, factory):
  6. self.factory = factory
  7.  
  8. def connectionMade(self):
  9. self.sendQuote()
  10.  
  11. def sendQuote(self):
  12. self.transport.write(b'self.factory.quote')
  13.  
  14. def dataReceived(self, data):
  15. print(f"Received quote: {data}")
  16. self.transport.loseConnection()
  17.  
  18.  
  19. class QuoteClientFactory(protocol.ClientFactory):
  20. def __init__(self, quote):
  21. self.quote = quote
  22.  
  23. def buildProtocol(self, addr):
  24. return QuoteProtocol(self)
  25.  
  26. def clientConnectionFailed(self, connector, reason):
  27. print("connecton failed:"), reason.getErrorMessage()
  28. maybeStopReactor()
  29.  
  30. def clientConnectionLost(self, connector, reason):
  31. print("connection lost"), reason.getErrorMessage()
  32. maybeStopReactor()
  33.  
  34.  
  35. def maybeStopReactor():
  36. global quote_counter
  37. quote_counter -= 1
  38. if not quote_counter:
  39. reactor.stop()
  40.  
  41. quotes = [
  42. "you snooze you lose",
  43. "The early bird gets the worm",
  44. "carpe diem"
  45. ]
  46.  
  47. quote_counter = len(quotes)
  48.  
  49. for quote in quotes:
  50. reactor.connectTCP('localhost', 10310, QuoteClientFactory(quote))
  51. reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment