Skip to content

Instantly share code, notes, and snippets.

@baburdick
Created December 10, 2010 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baburdick/735690 to your computer and use it in GitHub Desktop.
Save baburdick/735690 to your computer and use it in GitHub Desktop.
# Write a ASIR::Transport::HTTP class
# Using HTTP::Client for transport send_request and receive_response.
# Using WEBrick for transport on the receive_request and send_response.
# Use the Marshal Coder for the Transport.
require 'rubygems'
require 'webrick'
gem 'httpclient'
require 'httpclient'
require 'uri'
$: << File.expand_path("../../../lib", __FILE__)
require 'asir'
require 'math_service'
PORT = 3001
module ASIR
class Transport
class HTTP < self
attr_accessor :uri, :server
# Client-side: HTTPClient
def _send_request request
#$stderr.puts "\nrequest.inspect: #{request.inspect}"
client = ::HTTPClient.new
client.post uri, request
end
# Should extract the content from the HTTPClient::Message
def _receive_response opaque
#$stderr.puts "\nopaque.inspect: #{opaque.inspect}"
#$stderr.puts "\nopaque.content.inspect: #{opaque.content.inspect}"
opaque.content
end
# Server-side: WEBrick
# Extract the body from the request.
def _receive_request rq
#$stderr.puts "\nrq.inspect: #{rq.inspect}"
rq.body
end
# Set the Content-Type and body of the response.
def _send_response result, rs
#$stderr.puts "\nresult.inspect: #{result.inspect}"
#$stderr.puts "\nrs.inspect: #{rs.inspect}"
rs["Content-Type"] = "application/binary"
rs.body = result
end
# Parse the port and path of the #uri
# Create a @server = WEBrick::HTTPServer on the port
# Mount the path with a proc that calls serve_request! with the HTTP request and response objects.
def setup_server!
@server = WEBrick::HTTPServer.new :Port => PORT
@server.mount_proc "/" do |req,resp|
serve_request! req, resp
end
self
end
# Start the WEBbrick @server
def start_server!
@server.start
self
end
end
end
end
begin
t = ASIR::Transport::HTTP.new :uri => "http://localhost:#{PORT}/"
t._log_enabled = true
t.logger = $stderr
c = t.encoder = ASIR::Coder::Marshal.new
c._log_enabled = true
c.logger = $stderr
# Setup and run the server in a child process.
server_pid = Process.fork do
t.setup_server!
t.start_server!
end
# system("curl http://localhost:#{PORT}/")
MathService.client.transport = t
MathService.client.sum([1, 2, 3])
rescue Exception => err
puts err
puts err.backtrace.join "\n"
ensure
# Kill the server.
Process.kill(9, server_pid)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment