1 """Simple example of doing arbitarily long calculations nicely in Twisted.
3 This is also a simple demonstration of twisted.protocols.basic.LineReceiver.
6 from twisted.protocols import basic
7 from twisted.internet import reactor
8 from twisted.internet.protocol import ServerFactory
10 class LongMultiplicationProtocol(basic.LineReceiver):
11 """A protocol for doing long multiplications.
13 It receives a list of numbers (seperated by whitespace) on a line, and
14 writes back the answer. The answer is calculated in chunks, so no one
15 calculation should block for long enough to matter.
17 def connectionMade(self):
20 def lineReceived(self, line):
22 numbers = map(long, line.split())
24 self.sendLine('Error.')
28 self.sendLine('Error.')
31 self.workQueue.append(numbers)
32 reactor.callLater(0, self.calcChunk)
35 # Make sure there's some work left; when multiple lines are received
36 # while processing is going on, multiple calls to reactor.callLater()
37 # can happen between calls to calcChunk().
39 # Get the first bit of work off the queue
40 work = self.workQueue[0]
42 # Do a chunk of work: [a, b, c, ...] -> [a*b, c, ...]
43 work[:2] = [work[0] * work[1]]
45 # If this piece of work now has only one element, send it.
47 self.sendLine(str(work[0]))
50 # Schedule this function to do more work, if there's still work
53 reactor.callLater(0, self.calcChunk)
56 class LongMultiplicationFactory(ServerFactory):
57 protocol = LongMultiplicationProtocol
60 if __name__ == '__main__':
61 from twisted.python import log
63 log.startLogging(sys.stdout)
64 reactor.listenTCP(1234, LongMultiplicationFactory())