Ruby 简明教程

Web Services with Ruby - SOAP4R

What is SOAP?

简单对象访问协议(SOAP)是一个基于 XML,通常(但并非必须)基于 HTTP 的跨平台、与语言无关的 RPC 协议。

The Simple Object Access Protocol (SOAP), is a cross-platform and language-independent RPC protocol based on XML and, usually (but not necessarily) HTTP.

它使用 XML 对进行远程过程调用的信息进行编码,并使用 HTTP 通过网络将该信息从客户端传输到服务器,反之亦然。

It uses XML to encode the information that makes the remote procedure call, and HTTP to transport that information across a network from clients to servers and vice versa.

与 COM、CORBA 等其他技术相比,SOAP 具有若干优势:例如,它的部署和调试成本相对较低、具有可扩展性和易用性,并且为不同的语言和平台存在多种实现。

SOAP has several advantages over other technologies like COM, CORBA etc: for example, its relatively cheap deployment and debugging costs, its extensibility and ease-of-use, and the existence of several implementations for different languages and platforms.

请参阅我们的简单教程 SOAP 以详细了解它。

Please refer to our simple tutorial SOAP to understand it in detail.

本小节让你熟悉 Ruby 的 SOAP 实现(SOAP4R)。这是一本基础教程,因此如果你需要更深入了解,你需要参考其他资源。

This chapter makes you familiar with the SOAP implementation for Ruby (SOAP4R). This is a basic tutorial, so if you need a deep detail, you would need to refer other resources.

Installing SOAP4R

SOAP4R 是由 Hiroshi Nakamura 开发的 Ruby 的 SOAP 实现,可从以下位置下载:

SOAP4R is the SOAP implementation for Ruby developed by Hiroshi Nakamura and can be downloaded from −

NOTE − 已经安装此组件的可能性很大。

NOTE − There may be a great chance that you already have installed this component.

Download SOAP

如果您知道 gem 实用的功能,可以使用以下命令安装SOAP4R及其相关包。

If you are aware of gem utility then you can use the following command to install SOAP4R and related packages.

$ gem install soap4r --include-dependencies

如果您在Windows上工作,则需要从上述位置下载一个zip文件,并且需要使用标准安装方法通过运行ruby install.rb来安装它。

If you are working on Windows, then you need to download a zipped file from the above location and need to install it using the standard installation method by running ruby install.rb.

Writing SOAP4R Servers

SOAP4R支持两种不同类型的服务器−

SOAP4R supports two different types of servers −

  1. CGI/FastCGI based (SOAP::RPC::CGIStub)

  2. Standalone (SOAP::RPC:StandaloneServer)

本章提供了有关编写独立服务器的详细信息。在编写SOAP服务器中涉及以下步骤。

This chapter gives detail on writing a stand alone server. The following steps are involved in writing a SOAP server.

Step 1 - Inherit SOAP::RPC::StandaloneServer Class

要实施您自己的独立服务器,您需要编写一个新类,该类将成为SOAP::StandaloneServer的子类,如下所示:−

To implement your own stand alone server you need to write a new class, which will be child of SOAP::StandaloneServer as follows −

class MyServer < SOAP::RPC::StandaloneServer
  ...............
end

NOTE -如果您想编写基于FastCGI的服务器,则需要将SOAP::RPC::CGIStub作为父类,其余过程将保持不变。

NOTE − If you want to write a FastCGI based server then you need to take SOAP::RPC::CGIStub as parent class, rest of the procedure will remain the same.

Step 2 - Define Handler Methods

第二步是编写您希望向外界公开的Web服务方法。

Second step is to write your Web Services methods, which you would like to expose to the outside world.

它们可以作为简单的Ruby方法编写。例如,我们编写两个方法,将两个数字相加并除以两个数字−

They can be written as simple Ruby methods. For example, let’s write two methods to add two numbers and divide two numbers −

class MyServer < SOAP::RPC::StandaloneServer
   ...............

   # Handler methods
   def add(a, b)
      return a + b
   end
   def div(a, b)
      return a / b
   end
end

Step 3 - Expose Handler Methods

下一步是将我们定义的方法添加到服务器中。初始化方法用于使用以下两种方法之一公开服务方法:−

Next step is to add our defined methods to our server. The initialize method is used to expose service methods with one of the two following methods −

class MyServer < SOAP::RPC::StandaloneServer
   def initialize(*args)
      add_method(receiver, methodName, *paramArg)
   end
end

以下是参数说明 −

Here is the description of the parameters −

Sr.No.

Parameter & Description

1

receiver The object that contains the methodName method. You define the service methods in the same class as the methodDef method, this parameter is self.

2

methodName The name of the method that is called due to an RPC request.

3

paramArg Specifies, when given, the parameter names and parameter modes.

要理解inout或out参数的用法,请考虑以下服务方法,该服务方法采用两个参数(inParam和inoutParam),返回一个普通返回值(retVal)以及两个其他参数:inoutParam和outParam−

To understand the usage of inout or out parameters, consider the following service method that takes two parameters (inParam and inoutParam), returns one normal return value (retVal) and two further parameters: inoutParam and outParam −

def aMeth(inParam, inoutParam)
   retVal = inParam + inoutParam
   outParam = inParam . inoutParam
   inoutParam = inParam * inoutParam
   return retVal, inoutParam, outParam
end

现在,我们可以按以下方式公开此方法:−

Now, we can expose this method as follows −

add_method(self, 'aMeth', [
   %w(in inParam),
   %w(inout inoutParam),
   %w(out outParam),
   %w(retval return)
])

Step 4 - Start the Server

最后一步是通过实例化一个派生类的实例并调用 start 方法来启动服务器。

The final step is to start your server by instantiating one instance of the derived class and calling start method.

myServer = MyServer.new('ServerName', 'urn:ruby:ServiceName', hostname, port)

myServer.start

以下是所需参数的说明:−

Here is the description of required parameters −

Sr.No.

Parameter & Description

1

ServerName A server name, you can give what you like most.

2

urn:ruby:ServiceName Here urn:ruby is constant but you can give a unique ServiceName name for this server.

3

hostname Specifies the hostname on which this server will listen.

4

port An available port number to be used for the web service.

Example

现在,使用上述步骤,让我们编写一个独立服务器 −

Now, using the above steps, let us write one standalone server −

require "soap/rpc/standaloneserver"

begin
   class MyServer < SOAP::RPC::StandaloneServer

      # Expose our services
      def initialize(*args)
         add_method(self, 'add', 'a', 'b')
         add_method(self, 'div', 'a', 'b')
      end

      # Handler methods
      def add(a, b)
         return a + b
      end
      def div(a, b)
         return a / b
      end
end
   server = MyServer.new("MyServer",
            'urn:ruby:calculation', 'localhost', 8080)
   trap('INT){
      server.shutdown
   }
   server.start
rescue => err
   puts err.message
end

在执行时,此服务器应用程序在 localhost 上启动一个独立 SOAP 服务器,并侦听端口 8080 上的请求。它公开了一种服务方法,即加法和除法,该方法接受两个参数并返回结果。

When executed, this server application starts a standalone SOAP server on localhost and listens for requests on port 8080. It exposes one service methods, add and div, which takes two parameters and return the result.

现在,您可以按如下方式在后台运行此服务器 −

Now, you can run this server in background as follows −

$ ruby MyServer.rb&

Writing SOAP4R Clients

SOAP::RPC::Driver 类提供对编写 SOAP 客户端应用程序的支持。本章介绍此类,并根据一个应用程序演示其使用。

The SOAP::RPC::Driver class provides support for writing SOAP client applications. This chapter describes this class and demonstrate its usage on the basis of an application.

以下是调用 SOAP 服务所需的最基本信息 −

Following is the bare minimum information you would need to call a SOAP service −

  1. The URL of the SOAP service (SOAP Endpoint URL).

  2. The namespace of the service methods (Method Namespace URI).

  3. The names of the service methods and their parameters.

现在,我们将编写一个 SOAP 客户端,它将调用在上一个示例中定义的服务方法,即加法和除法。

Now, we will write a SOAP client which would call service methods defined in above example, named add and div.

以下是创建 SOAP 客户端的主要步骤。

Here are the main steps to create a SOAP client.

Step 1 - Create a SOAP Driver Instance

我们通过调用 new 方法按照如下方式创建 SOAP::RPC::Driver 的一个实例 −

We create an instance of SOAP::RPC::Driver by calling its new method as follows −

SOAP::RPC::Driver.new(endPoint, nameSpace, soapAction)

以下是所需参数的说明:−

Here is the description of required parameters −

Sr.No.

Parameter & Description

1

endPoint URL of the SOAP server to connect with.

2

nameSpace The namespace to use for all RPCs done with this SOAP::RPC::Driver object.

3

soapAction A value for the SOAPAction field of the HTTP header. If nil this defaults to the empty string "".

Step 2 - Add Service Methods

若要向 SOAP::RPC::Driver 添加 SOAP 服务方法,我们可以使用 SOAP::RPC::Driver 实例调用如下方法 −

To add a SOAP service method to a SOAP::RPC::Driver we can call the following method using SOAP::RPC::Driver instance −

driver.add_method(name, *paramArg)

以下是参数说明 −

Here is the description of the parameters −

Sr.No.

Parameter & Description

1

name The name of the remote web service method.

2

paramArg Specifies the names of the remote procedures' parameters.

Step 3 - Invoke SOAP service

最后一步是使用 SOAP::RPC::Driver 实例调用 SOAP 服务,如下所示 −

The final step is to invoice SOAP service using SOAP::RPC::Driver instance as follows −

result = driver.serviceMethod(paramArg...)

在其中,serviceMethod 为实际的 Web 服务方法,paramArg…​​ 是需在服务方法中传递的参数列表。

Here serviceMethod is the actual web service method and paramArg…​ is the list parameters required to pass in the service method.

Example

根据上述步骤,我们编写 SOAP 客户端,如下所示:

Based on the above steps, we will write a SOAP client as follows −

#!/usr/bin/ruby -w

require 'soap/rpc/driver'

NAMESPACE = 'urn:ruby:calculation'
URL = 'http://localhost:8080/'

begin
   driver = SOAP::RPC::Driver.new(URL, NAMESPACE)

   # Add remote sevice methods
   driver.add_method('add', 'a', 'b')

   # Call remote service methods
   puts driver.add(20, 30)
rescue => err
   puts err.message
end

Further Readings

我刚刚解释了 Web 服务与 Ruby 的基本概念。如果您希望进一步深入了解,可以访问以下链接,以查找更多有关 Web Services with Ruby 的详细信息。

I have explained you just very basic concepts of Web Services with Ruby. If you want to drill down it further, then there is following link to find more details on Web Services with Ruby.