Advertisement
poachedeggs

Solution to client 4.0 exercise 1 plus 2

Jan 24th, 2018
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #### Changed class PoetryProtocol from twisted-client-4\get-poetry.py
  2.  
  3. class PoetryProtocol(Protocol):
  4.  
  5. poem = ''
  6. timeoutVal = 2
  7.  
  8. def dataReceived(self, data):
  9. self.poem += data
  10.  
  11. def connectionLost(self, reason):
  12. if self.timeoutFn.active():
  13. # ok: timeout not triggered
  14. self.timeoutFn.cancel()
  15. self.poemReceived(self.poem)
  16. else:
  17. # nok: timed out
  18. self.poemNotRxd(Exception('Time out'))
  19.  
  20. def poemReceived(self, poem):
  21. self.factory.poem_finished(poem)
  22.  
  23. def poemNotRxd(self, reason):
  24. self.factory.clientConnectionFailed(self.transport.connector, reason)
  25.  
  26. def connectionMade(self):
  27. from twisted.internet import reactor
  28. self.timeoutFn = reactor.callLater(self.timeoutVal, self.transport.loseConnection)
  29.  
  30. #### Changed poetry_main() from twisted-client-4\get-poetry.py
  31.  
  32. def poetry_main():
  33. addresses = parse_args()
  34.  
  35. from twisted.internet import reactor
  36.  
  37. poems = []
  38. errors = []
  39.  
  40. def got_poem(poem):
  41. poems.append(poem)
  42.  
  43. def poem_failed(err, host, port):
  44. print >>sys.stderr, 'Poem failed on %s:%d:' % (host, port), err
  45. errors.append(err)
  46.  
  47. def poem_done(_):
  48. if len(poems) + len(errors) == len(addresses):
  49. reactor.stop()
  50.  
  51. for address in addresses:
  52. host, port = address
  53. d = get_poetry(host, port)
  54. d.addCallbacks(got_poem, poem_failed, errbackArgs=(host, port))
  55. d.addBoth(poem_done)
  56.  
  57. reactor.run()
  58.  
  59. for poem in poems:
  60. print poem
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement