welcome: please sign in
location: SumClientServer

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):
    arguments = [('a', amp.Integer()),
                 ('b', amp.Integer())]
    response = [('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()

And 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 = [('a', amp.Integer()),
                 ('b', amp.Integer())]
    response = [('total', amp.Integer())]

def connected(protocol):
    return protocol.callRemote(Sum, a=13, b=81
        ).addCallback(gotResult)

def gotResult(result):
    print 'total:', 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

And you should see it print out the result of the addition.

SumClientServer (last edited 2010-11-09 17:37:50 by teratorn)

Website maintained by, and © 2010 Eric P. Mangold. Some content © 2010 Twisted Matrix Labs