[Twisted-web] Newbie Question? -- Running xmlrpc client and server together

John C Lin twisted-web@twistedmatrix.com
Wed, 28 Jan 2004 14:27:41 -0800 (PST)


Hi,

I have run around the on-line documentation for twisted and couldn't find
the relevant docs to help my case.  If anyone has pointers on what to
read, I would gladly read those documents first.

Here is the question:  I want to run a xmlrpc server and client together.  
That is, in the same program, I want to be able to listen from other 
clients that are calling my xmlrpc methods, and from time to time, I want 
to call the other clients' xmlrpc methods as well.

>From the examples I can find, a server is run by invoking an application's 
run method, while a client is run by invoking the reactor's run method.  
How can I "register" my own event loop in addition to the application's 
already existing xmlrpc server that I have added earlier?  

For example, let's say I have two clients that implement the adder xmlrpc 
method (returns the sum of two numbers).  I want the clients to call each 
other's adder method every two seconds.  Below is the server sample code 
from Victor Ng that I am looking at (I only added some code to read 
arguments from the command line):


from twisted.internet import reactor, defer
from twisted.web import xmlrpc, server, resource
from twisted.enterprise import adbapi

import sys

if len (sys.argv) >= 5:
  player_id      = int (sys.argv[1])
  port_num       = int (sys.argv[2])
  num_players    = int (sys.argv[3])
  start_port_num = int (sys.argv[4])

print "Starting agents.py with player_id: %d, port_num: %d, num_players: 
%d, start_port_num: %d\n" % (player_id,         port_num, num_players, 
start_port_num)


class XMLRPCAdder(xmlrpc.XMLRPC):
  """
  An example object to be published
  """
  def run_add(self, d, a, b):
    d.callback(a+b)

  def marshallResult(self, data):
    return "[%s]" % str(data)

  def xmlrpc_add(self, a, b):
    d = defer.Deferred()

    # setup a callback in 2 seconds that executes the callback on the deferred
    reactor.callLater(2, self.run_add, d, a, b)

    return d.addCallback(self.marshallResult)

def main():
  from twisted.internet.app import Application
  app = Application("simpleDemoServer")
  root = resource.Resource()
  child = XMLRPCAdder()
  root.putChild('RPC2', child)
  app.listenTCP(port_num, server.Site(root))
  return app

application = main()

if __name__ == '__main__':
  application.run(save = 0)



Thanks in advance.
John Lin