Python 2.x/3.x example code for a Sum
server and client.¶
Save this in to a file sum_server.py
:
# Server implementation for a "Sum" command which adds two integers
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
class Sum(amp.Command):
# normally shared by client and server code
arguments = [(b'a', amp.Integer()),
(b'b', amp.Integer())]
response = [(b'total', amp.Integer())]
class Protocol(amp.AMP):
@Sum.responder
def sum(self, a, b):
return {'total': a+b}
pf = Factory()
pf.protocol = Protocol
reactor.listenTCP(1234, pf) # listen on port 1234
reactor.run()
Save this in to a file sum_client.py
:
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
class Sum(amp.Command):
# normally shared by client and server code
arguments = [(b'a', amp.Integer()),
(b'b', amp.Integer())]
response = [(b'total', amp.Integer())]
def connected(protocol):
return protocol.callRemote(Sum, a=13, b=81
).addCallback(gotResult)
def gotResult(result):
print('total: %d' % (result['total'],))
reactor.stop()
def error(reason):
print("Something went wrong")
print(reason)
reactor.stop()
ClientCreator(reactor, amp.AMP).connectTCP(
'127.0.0.1', 1234).addCallback(connected).addErrback(error)
reactor.run()
Open two terminal windows. In the first, type this:
python sum_server.py
Then in the second, type:
python sum_client.py
The result of the addition should be printed on your screen!