SOAP(Simple Object Access Protocol)是跨平台、語言中立的 XML 型 RPC 協定。Ruby SOAP4R 函式庫支援建立獨立或 CGI/FastCGI 型 SOAP Server,以及 Client 呼叫。本文詳細說明 Server 繼承、方法暴露、啟動流程,以及 Client 驅動建立與呼叫步驟。
gem install soap4r --include-dependencies
SOAP::RPC::StandaloneServeradd, div)initialize 中用 add_method 暴露方法startrequire "soap/rpc/standaloneserver"
class MyServer < SOAP::RPC::StandaloneServer
def initialize(*args)
super
add_method(self, 'add', 'a', 'b')
add_method(self, 'div', 'a', 'b')
end
def add(a, b); a + b; end
def div(a, b); a / b; end
end
server = MyServer.new("MyServer", 'urn:ruby:calculation', 'localhost', 8080)
trap('INT') { server.shutdown }
server.start
ruby MyServer.rb &
SOAP::RPC::Driver 實例add_method 加入遠端方法require 'soap/rpc/driver'
driver = SOAP::RPC::Driver.new('https://localhost:8080/', 'urn:ruby:calculation')
driver.add_method('add', 'a', 'b')
driver.add_method('div', 'a', 'b')
puts driver.add(5, 3) # => 8
puts driver.div(10, 2) # => 5
add_method 參數模式:%w(in param)、%w(inout param)、%w(out param)、%w(retval return),支援輸入/輸出/輸入輸出/回傳值。
注意: SOAP4R 已停止維護,現代專案建議使用 REST/JSON API 或 savon、handsoap 等較新的 SOAP 函式庫。