Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
XMLRPC server and client modules in Python
XML-RPC (XML Remote Procedure Call) is a protocol that allows programs to make function calls over HTTP using XML for encoding. Python's xmlrpc.server and xmlrpc.client modules make it easy to create cross-platform, language-independent servers and clients.
Creating an XML-RPC Server
We use SimpleXMLRPCServer to create a server instance and register functions that clients can call remotely. The server listens for incoming requests and executes the appropriate functions ?
Example
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
with SimpleXMLRPCServer(('localhost', 9000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()
# Register len() function
server.register_function(len)
# Register a function under a different name
@server.register_function(name='rmndr')
def remainder_function(x, y):
return x // y
# Register a function under function.__name__
@server.register_function
def modl(x, y):
return x % y
print("Server running on localhost:9000...")
server.serve_forever()
Key Components
The server setup involves several important components:
- RequestHandler: Defines the RPC path ('/RPC2')
-
register_introspection_functions(): Enables system methods like
listMethods() - register_function(): Registers functions with optional custom names
- serve_forever(): Puts server in infinite loop to handle requests
Creating an XML-RPC Client
The client connects to the server using xmlrpc.client.ServerProxy and can call registered functions as if they were local ?
Example
import xmlrpc.client
# Connect to the server
s = xmlrpc.client.ServerProxy('http://localhost:9000')
print(s.len("Tutorialspoint"))
print(s.rmndr(12, 5))
print(s.modl(7, 3))
# Print list of available methods
print(s.system.listMethods())
Output
Running the above client code gives us the following result ?
14 2 1 ['len', 'modl', 'rmndr', 'system.listMethods', 'system.methodHelp', 'system.methodSignature']
How It Works
The XML-RPC protocol works by:
- Client sends HTTP POST request with XML-encoded function call
- Server receives request, decodes XML, and executes function
- Server encodes result as XML and sends HTTP response
- Client receives and decodes the XML response
Conclusion
XML-RPC provides a simple way to create distributed applications in Python. The server registers functions that clients can call remotely over HTTP, making it ideal for cross-platform communication between different programming languages.
