SOAP及WebServices

孤獨的貓董發表於2008-09-10

我們可以通過SOAP伺服器來訪問預先定義好的物件,通過soap/rpc/driver就可做到,這也可以看作是同其他語言互動的一種很好的方式,伺服器端存為server.rb

require `soap/rpc/standaloneServer`

class InterestCalculator
  attr_reader :call_count
  def initialize
    @call_count=0
  end
  def compound(printcipal,rate,freq,years)
    @call_count+=1
    printcipal*(1.0+rate/freq)**(freq*years)
  end
end

NS=`http://pragprog.com/InterestCalc`
class Server2<SOAP::RPC::StandaloneServer
  def on_init
    calc=InterestCalculator.new
    add_method(calc,`compound`,`printcipal`,`rate`,`freq`,`years`)
    add_method(calc,`call_count`)
  end
end
svr=Server2.new(`Calc`,NS,`0.0.0.0`,12321)
trap(`INT`){svr.shutdown}
svr.start

客戶端程式碼存為client.rb
require `soap/rpc/driver`
proxy=SOAP::RPC::Driver.new(“http://localhost:12321″,”http://pragprog.com/InterestCalc”)
proxy.add_method(`compound`,`principle`,`rate`,`freq`,`years`)
proxy.add_method(`call_count`)
puts “Call count: #{proxy.call_count}”
puts “5 years,compound annually: #{proxy.compound(100,0.06,1,5)}”
puts “5 years,compound monthly: #{proxy.compound(100,0.06,12,5)}”
puts “Call count: #{proxy.call_count}”

我們在伺服器端輸入

% ruby server.rb

以開啟伺服器

客戶端中輸入

%ruby client.rb

會顯示

Call count:0

5 years,compound annually:133.8225776

…….


相關文章