Implement an XML-RPC-Based Web Service
First, you need to write a simple
XML-RPC client. You frequently will want to access other services that support an XML-RPC interface, so all you need to know is how to write clients. (However, you shortly will see how to also write XML-RPC services in Ruby.)
The Ruby built-in XML-RPC library automatically marshals values in Ruby variables to and from XML. This example uses string arguments, but arguments could also be numbers, arrays, etc. The following client accesses the services "upper_case" and "lower_case" from a server that supports XML-RPC and implements these services:
Listing 7
require 'xmlrpc/client'
server = XMLRPC::Client.new("127.0.0.1", "/RPC2", 9090)
puts server.call("upper_case", "The fat dog chased the cat on Elm Street.")
puts server.call("lower_case", "The fat dog chased the cat on Elm Street.")
I have written XML-RPC services in Java, Common Lisp, Python, and Perl. I think that, using the WEBrick classes, Ruby's XML-RPC library is the easiest to use. Here is server code that would process calls for the code in Listing 7:
Listing 8
require 'webrick'
require 'xmlrpc/server.rb'
# create a servlet to handle XML-RPC requests:
servlet = XMLRPC::WEBrickServlet.new
servlet.add_handler("upper_case") { |a_string| a_string.upcase }
servlet.add_handler("lower_case") { |a_string| a_string.downcase }
# create a WEBrick instance to host this servlet:
server=WEBrick::HTTPServer.new(:Port => 9090)
trap("INT"){ server.shutdown }
server.mount("/RPC2", servlet)
server.start
You can add any number of named handlers to a WEBrickServlet. These handlers can take zero or more arguments.