XML-RPC makes calling remote functions incredibly easy.
From http://www.xml-rpc.com: It's a spec and a set of implementations that allow software running on disparate operating systems, running in different environments to make procedure calls over the Internet. It's remote procedure calling using HTTP as the transport and XML as the encoding. XML-RPC is designed to be as simple as possible, while allowing complex data structures to be transmitted, processed and returned.
Here is a bit of sample code to call a procedure message (passing in the first argument) on a server listening on localhost, port 8000:
1 # messageclient.py
2
3 import xmlrpclib
4 import sys
5
6 if len(sys.argv) > 1:
7 s = xmlrpclib.ServerProxy('http://localhost:8000')
8 s.message(sys.argv[1])
(also, see this example and the xmlrpclib documentation)
Here is a simple server which implements the above message procedure as well as a wait procedure. This server is based on the DocXMLRPCServer included with Python2.3; In Python2.2, use SimpleXMLRPCServer instead, and don't call server.register_introspection_functions().
1 # ExampleServer.py
2 import time
3 import socket
4 from DocXMLRPCServer import DocXMLRPCServer
5
6 class SimpleShareServer:
7 def message(self, msg):
8 """message('Print me!') => True
9
10 Log everything passed to this function"""
11 print time.asctime(), msg
12 return True
13
14 def wait(self, seconds):
15 """wait(5) => 5
16
17 Wait for a certain number of seconds before returning.
18 Returns the same number passed in."""
19 print time.asctime(), "Waiting %s seconds" % seconds
20 time.sleep(seconds)
21 print time.asctime(), "Finished waiting %s seconds" % seconds
22 return seconds
23
24
25 if __name__ == '__main__':
26 server = DocXMLRPCServer(("localhost", 8000), logRequests=0)
27 server.register_introspection_functions()
28 server.register_instance(SimpleShareServer())
29
30 print time.asctime(), 'Application Starting.'
31 server.serve_forever()
32 print time.asctime(), 'Application Finishing.'
The benefit of using DocXMLRPCServer is that it automatically creates documentation for your XML-RPC server, just open a browser and head to http://localhost:8000 after starting the server.
Writing a client to call the wait function is left as an exercise for the reader.
Resources
- Also read the comments in both SimpleXMLRPCServer.py, and DocXMLRPCServer.py - they contain many examples of how to use the modules.
Fast C implementation of xmlrpc for python (only for python version up to 2.2)