Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This is the Twisted Get Poetry Now! client, version 2.0.
- # NOTE: This should not be used as the basis for production code.
- import datetime, optparse
- from twisted.internet.protocol import Protocol, ClientFactory
- def parse_args():
- usage = """usage: %prog [options] [hostname]:port ...
- This is the Get Poetry Now! client, Twisted version 2.0.
- Run it like this:
- python get-poetry.py port1 port2 port3 ...
- If you are in the base directory of the twisted-intro package,
- you could run it like this:
- python twisted-client-2/get-poetry.py 10001 10002 10003
- to grab poetry from servers on ports 10001, 10002, and 10003.
- Of course, there need to be servers listening on those ports
- for that to work.
- """
- parser = optparse.OptionParser(usage)
- _, addresses = parser.parse_args()
- if not addresses:
- print parser.format_help()
- parser.exit()
- def parse_address(addr):
- if ':' not in addr:
- host = '127.0.0.1'
- port = addr
- else:
- host, port = addr.split(':', 1)
- if not port.isdigit():
- parser.error('Ports must be integers.')
- return host, int(port)
- return map(parse_address, addresses)
- class PoetryProtocol(Protocol):
- poem = ''
- task_num = 0
- # called as soon as client read it by TCP (doRead())
- def __init__(self, timeout_period = None):
- object.__init__(self)
- self.delayed_call = None
- self.timeout_period = timeout_period or 20
- def dataReceived(self, data):
- # import sys, traceback, os
- # traceback.print_stack()
- # os._exit(0)
- self.poem += data
- msg = 'Task %d: got %d bytes of poetry from %s'
- print msg % (self.task_num, len(data), self.transport.getPeer())
- # this callback called either if poem read is finished or
- # task is timeout
- # first case: connectionLost called by twisted.internet.tcp.py module in readConnectionLost callback:
- # in posixbase : in _doReadOrWrite disconnects our client
- def connectionLost(self, reason):
- import sys, traceback, os
- traceback.print_stack()
- os._exit(0)
- self.poemReceived(self.poem)
- print reason
- def timeout_task(self):
- print "%d task timed out" % self.task_num
- self.transport.loseConnection()
- def connectionMade(self):
- from twisted.internet import reactor
- self.delayed_call = reactor.callLater(self.timeout_period, self.timeout_task)
- def success(self):
- if self.delayed_call is None: return
- self.delayed_call.cancel()
- print 'task sucecssfully finished!'
- def poemReceived(self, poem):
- self.factory.poem_finished(self.task_num, poem)
- self.success
- class PoetryClientFactory(ClientFactory):
- task_num = 1
- protocol = PoetryProtocol # tell base class what proto to build
- def __init__(self, poetry_count):
- self.poetry_count = poetry_count
- self.poems = {} # task num -> poem
- # called if timeout
- # def postpone_task(self, task_num = None, poem = None):
- # print "%d task has been posponed" %(task_num)
- # (task_num, poem)
- def buildProtocol(self, address):
- # tries to connection protocol to transport by address
- proto = ClientFactory.buildProtocol(self, address)
- proto.task_num = self.task_num
- self.task_num += 1
- # if something goes wrong call it later
- return proto
- def poem_finished(self, task_num=None, poem=None):
- if task_num is not None:
- self.poems[task_num] = poem
- self.poetry_count -= 1
- if self.poetry_count == 0:
- self.report()
- from twisted.internet import reactor
- reactor.stop()
- def report(self):
- for i in self.poems:
- print 'Task %d: %d bytes of poetry' % (i, len(self.poems[i]))
- def clientConnectionFailed(self, connector, reason):
- print 'Failed to connect to:', connector.getDestination()
- self.poem_finished()
- def poetry_main():
- addresses = parse_args()
- start = datetime.datetime.now()
- # builds client instance of protocol
- factory = PoetryClientFactory(len(addresses))
- from twisted.internet import reactor
- for address in addresses:
- host, port = address
- # connect a tcp client with (host, port) and factory
- # raises some callbacks like clientCOnnectionFailed or --made
- reactor.connectTCP(host, port, factory)
- reactor.run()
- elapsed = datetime.datetime.now() - start
- print 'Got %d poems in %s' % (len(addresses), elapsed)
- if __name__ == '__main__':
- poetry_main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement