Writing a SOAP Server

Credit: Kevin Marshall

Problem

You want to host a SOAP-based web service using a standalone server (that is, not as part of a Rails application).

Solution

Building your own SOAP server really only requires three simple steps:

  1. Subclass the SOAP::StandaloneServer class. In the constructor, register the methods you want to expose and the arguments they should take. Here we expose a method sayhelloto method that expects one parameter, username:

    require soap/rpc/standaloneServer class MyServer < SOAP::RPC::StandaloneServer def initialize(*args) super add_method(self, sayhelloto, username) end end

  2. Define the methods you exposed in step 1:

    class MyServer def sayhelloto(username) "Hello, #{username}." end end

  3. Finally, set up and start your server. Our example server runs on port 8888 on localhost. Its name is "CoolServer" and its namespace is "urn:mySoapServer":

    server = MyServer.new(CoolServer,urn:mySoapServer,localhost,8888) trap(INT) { server.shutdown } server.start

    We trap interrupt signals so that we can stop our server from the command line.

Discussion

Weve now built a complete SOAP server. It uses the SOAP StandaloneServer and hosts one simple sayhelloto method that can be accessed at "http://localhost:8888/sayhelloto" with a namespace of "urn:mySoapServer".

To test your service, start your server in one Ruby session and then use the simple script below in another Ruby session to call the method it exposes:

require soap/rpc/driver driver = SOAP::RPC::Driver.new(http://localhost:8888/, urn:mySoapServer) driver.add_method(sayhelloto, username) driver.sayhelloto(Kevin) # => "Hello, Kevin."

See Also

Категории