Simple XMLRPC server in Ruby using WEBrick
Posted by tom February 23rd, 2006
Besides RAILS, I’m very interested in the Ruby language. I’m also curious how to setup a very simple XMLRPC server. I know WEBrick is a pretty stable and very extensible webserver (written in Ruby), as it can also run the RAILS software.
Below are two very simple little Ruby programs, one is the client, one is the server. The server is capable of adding, substracting, dividing & multiplying two numbers. It is also capable of throwing an error in case you try to divide by zero.
The client is capable of error handling. This should be a very simple starting point from which you can addon to build your own XMLRPC server.
The server:require "webrick"
require "xmlrpc/server"
class SimpleXMLRPC < XMLRPC::WEBrickServlet
def add( a, b )
a + b
end
def sub( a, b )
a - b
end
def div( a, b )
if b == 0
raise XMLRPC::FaultException.new(1, "Division by zero")
else
a / b
end
end
def mul( a, b )
a * b
end
end
h = SimpleXMLRPC.new
h.add_handler( "api", h )
httpserver = WEBrick::HTTPServer.new(:Port => 8080)
httpserver.mount("/", h)
trap("HUP") { httpserver.shutdown }
httpserver.start
The client:
require "xmlrpc/client"
# Make an object to represent the XML-RPC server.
server = XMLRPC::Client.new( "localhost", "/", 8080 )
# Call the xmlrpc server to try and add two numbers
begin
result = server.call("api.add", 5, 3)
puts "Sum of 5 & 3: #{result}"
rescue XMLRPC::FaultException => e
puts "Error:"
puts e.faultCode
puts e.faultString
end
# Call the xmlrpc server to try and divide two numbers
begin
result = server.call("api.div", 5, 0)
puts "Division of 5 & 0: #{result}"
rescue XMLRPC::FaultException => e
puts "Error:"
puts e.faultCode
puts e.faultString
end

August 16th, 2007 at 03:07 PM
Большое спасибо за примерчик думаю что он мне будет полезен в будующем