Skip to content

Instantly share code, notes, and snippets.

@exarkun
Forked from Drvanon/ampclient.py
Created May 2, 2012 15:55
Show Gist options
  • Save exarkun/2577729 to your computer and use it in GitHub Desktop.
Save exarkun/2577729 to your computer and use it in GitHub Desktop.
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from ampserver import Sum, Divide
def doMath():
try:
a = raw_input('What number for a ? \n >')
b = raw_input('What number for b? \n >')
a = int(a)
b = int(b)
except ValueError:
print 'That\'s not a number.'
doMath()
cc = ClientCreator(reactor, amp.AMP)
def doSum(proto):
return proto.callRemote(Sum, a=a, b=b)
def getTotal(result):
return result['total']
d1 = cc.connectTCP('192.168.2.10', 1234)
d1.addCallback(doSum)
d1.addCallback(getTotal)
def trapZero(result):
result.trap(ZeroDivisionError)
print "Divided by zero: returning INF"
return 1e1000
d2 = ClientCreator(reactor, amp.AMP).connectTCP(
'192.168.2.10', 1234).addCallback(
lambda p: p.callRemote(Divide, numerator=1234,
denominator=0)).addErrback(trapZero)
def done(result):
print 'Done with math:', result
d = defer.Deferred()
d.addCallback(done(d2))
if __name__ == '__main__':
doMath()
reactor.run()
from twisted.protocols import amp
class Sum(amp.Command):
arguments = [('a', amp.Integer()),
('b', amp.Integer())]
response = [('total', amp.Integer())]
class Divide(amp.Command):
arguments = [('numerator', amp.Integer()),
('denominator', amp.Integer())]
response = [('result', amp.Float())]
errors = {ZeroDivisionError: 'ZERO_DIVISION'}
class Math(amp.AMP):
def sum(self, a, b):
total = a + b
print 'Did a sum: %d + %d = %d' % (a, b, total)
return {'total': total}
Sum.responder(sum)
def divide(self, numerator, denominator):
result = float(numerator) / denominator
print 'Divided: %d / %d = %f' % (numerator, denominator, result)
return {'result': result}
Divide.responder(divide)
def main():
from twisted.internet import reactor
from twisted.internet.protocol import Factory
pf = Factory()
pf.protocol = Math
reactor.listenTCP(1234, pf)
print 'started'
reactor.run()
if __name__ == '__main__':
main()
Done with math: <Deferred at 0xb6de5d8cL>
Traceback (most recent call last):
File "ampclient.py", line 35, in <module>
doMath()
File "ampclient.py", line 32, in doMath
d.addCallback(done(d2))
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 298, in addCallback
callbackKeywords=kw)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 280, in addCallbacks
assert callable(callback)
AssertionError
# client
python ampclient.py
What number for a ?
>123
What number for b?
>123
# server
python ampserver.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment