Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / howto / listings / trial / calculus / client_3.py
1 # -*- test-case-name: calculus.test.test_client -*-
2
3 from twisted.protocols import basic, policies
4 from twisted.internet import defer
5
6
7
8 class ClientTimeoutError(Exception):
9     pass
10
11
12
13 class RemoteCalculationClient(object, basic.LineReceiver, policies.TimeoutMixin):
14
15     def __init__(self):
16         self.results = []
17         self._timeOut = 60
18
19     def lineReceived(self, line):
20         self.setTimeout(None)
21         d = self.results.pop(0)
22         d.callback(int(line))
23
24
25     def timeoutConnection(self):
26         for d in self.results:
27             d.errback(ClientTimeoutError())
28         self.transport.loseConnection()
29
30
31     def _sendOperation(self, op, a, b):
32         d = defer.Deferred()
33         self.results.append(d)
34         line = "%s %d %d" % (op, a, b)
35         self.sendLine(line)
36         self.setTimeout(self._timeOut)
37         return d
38
39
40     def add(self, a, b):
41         return self._sendOperation("add", a, b)
42
43
44     def subtract(self, a, b):
45         return self._sendOperation("subtract", a, b)
46
47
48     def multiply(self, a, b):
49         return self._sendOperation("multiply", a, b)
50
51
52     def divide(self, a, b):
53         return self._sendOperation("divide", a, b)