Ruby Programming Language Enables Concise Network Programming

Ruby Programming Language Enables Concise Network Programming

1. 웹 서버

require 'socket'
server = TCPServer.new('127.0.0.1', 9090)
while (session = server.accept)
  request = session.gets
  puts request
  session.print "HTTP/1.1 200/OK\rContent-type: text/html\r\n\r\n"
  session.print "<html><head><title>Response from Ruby Web server</title></head>\r\n"
  session.print "<body>request was:"
  session.print request
  session.print "</body></html>"
  session.close
end

2. URL을 파일처럼

require 'open-uri' # allows the use of a file like API for URLs
open("http://127.0.0.1:9090/foo?bar=123") { |file|
  lines = file.read
  puts lines
}

3. WEBrick Webserver

require 'webrick'
include WEBrick

s = HTTPServer.new(:Port => 9090,
                   :DocumentRoot => Dir::pwd + "/htdocs")
trap("INT"){ s.shutdown }
s.start

4. XML-RPC 클라이언트

require 'xmlrpc/client'
server = XMLRPC::Client.new("127.0.0.1", "/RPC2", 9090)
puts server.call("upper_case", "The fat dog chased the cat on Elm Street.")
puts server.call("lower_case", "The fat dog chased the cat on Elm Street.")

5. 4번의 클라이언트가 접속 가능한 XML-RPC 서버

require 'webrick'
require 'xmlrpc/server.rb'

# create a servlet to handle XML-RPC requests:
servlet = XMLRPC::WEBrickServlet.new
servlet.add_handler("upper_case") { |a_string| a_string.upcase }
servlet.add_handler("lower_case") { |a_string| a_string.downcase }

# create a WEBrick instance to host this servlet:
server=WEBrick::HTTPServer.new(:Port => 9090)
trap("INT"){ server.shutdown }
server.mount("/RPC2", servlet)
server.start

6. XML Webservices 클라이언트

require 'soap/rpc/driver'
stub = SOAP::RPC::Driver.new("http://127.0.0.1:9090", "http://markwatson.com/Demo")
stub.add_method('upper_case', 'a_string')
stub.add_method('lower_case', 'a_string')
stub.add_method('times_string', 'a_string', 'a_number')

puts stub.lower_case("Jack and Jill went up the hill.")
puts stub.upper_case("Jack and Jill went up the hill.")
puts stub.times_string("Jack and Jill went up the hill.", 2)

7. 6번의 클라이언트가 접속할 수 있는 XML Webservices 서버

require ‘soap/rpc/standaloneserver’

# define a class that has three methods to call remotely:

class DemoClass
def upper_case(a_string)
a_string.upcase
end
def lower_case(a_string)
a_string.downcase
end
def times_string(a_string, a_number)
a_string * a_number
end
end

# create a SOAP enabled server for the methods in DemoClass:

class MyServer < SOAP::RPC::StandaloneServer def on_init demo = DemoClass.new add_method(demo, "upper_case", "a_string") add_method(demo, "lower_case", "a_string") add_method(demo, "times_string", "a_string", "a_number") end end server = MyServer.new("Demo", "http://markwatson.com/Demo", "0.0.0.0", 9090) trap('INT') { server.shutdown } server.start [/code]

Similar Posts:

Post a Comment

Your email is never published nor shared.