Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 67af5b0f07
Fetching contributors…

Cannot retrieve contributors at this time

file 87 lines (64 sloc) 1.509 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
require 'rubygems'
require 'eventmachine'
require 'msgpack'
require 'benchmark'

# Server that receives MessagePack RPC
class MessagePipeServer < EventMachine::Connection
  CMD_CALL = 0x01
  RET_OK = 0x02
  RET_E = 0x03

  protected

  def pac
    @pac ||= MessagePack::Unpacker.new # Stream Deserializer
  end

  def receive_data(data)
    pac.feed(data)
    pac.each do |msg|
      begin

        response = nil

        secs = Benchmark.realtime do
          response = begin
            [RET_OK, receive_object(msg)]
          rescue => e
            [RET_E, "#{e.class.name}: #{e.message}"]
          end
        end

        send_data(response.to_msgpack)
        
        puts "#{object_id} - #{msg[1]}(#{msg[2].length} args) - [%.4f ms] [#{response[0] == RET_OK ? 'ok' : 'error'}]" % [secs||0]
        
      end
    end
  end

  def receive_object(msg)
    cmd, method, args = *msg

    if cmd != CMD_CALL
      unbind
      raise 'Bad client'
    end

    
    if method and public_methods.include?(method)
      return __send__(method, *args)
    else
      raise NoMethodError, "no method #{method} found."
    end
  end
end

class TestServer < MessagePipeServer

  def add(a, b)
    a + b
  end

  def hi
    'hello'
  end

  def echo(string)
    string
  end


  def throw
    raise StandardError, 'hell'
  end

  private

  def private_method
    'oh no'
  end

end

EventMachine::run do
  EventMachine::start_server "0.0.0.0", 9191, TestServer
end
Something went wrong with that request. Please try again.