Skip to content

Commit

Permalink
Add ObjectProtocol
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm1 committed Mar 15, 2009
1 parent 9ecc187 commit ae7cf7c
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/em/protocols.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module EventMachine
# - LineAndTextProtocol and LineText2
# - HeaderAndContentProtocol
# - Postgres3
# - ObjectProtocol
#
# The protocol implementations live in separate files in the protocols/ subdirectory,
# but are auto-loaded when they are first referenced in your application.
Expand All @@ -29,5 +30,6 @@ module Protocols
autoload :SASLauth, 'em/protocols/saslauth'
autoload :Memcache, 'em/protocols/memcache'
autoload :Postgres3, 'em/protocols/postgres3'
autoload :ObjectProtocol, 'em/protocols/object_protocol'
end
end
39 changes: 39 additions & 0 deletions lib/em/protocols/object_protocol.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
module EventMachine
module Protocols
# ObjectProtocol allows for easy communication using marshaled ruby objects
#
# module RubyServer
# include EM::P::ObjectProtocol
#
# def receive_object obj
# send_object({'you said' => obj})
# end
# end
#
module ObjectProtocol
def receive_data data # :nodoc:
(@buf ||= '') << data

while @buf.size >= 4
if @buf.size >= 4+(size=@buf.unpack('N').first)
@buf.slice!(0,4)
receive_object Marshal.load(@buf.slice!(0,size))
else
break
end
end
end

# Invoked with ruby objects received over the network
def receive_object obj
# stub
end

# Sends a ruby object over the network
def send_object obj
data = Marshal.dump(obj)
send_data [data.respond_to?(:bytesize) ? data.bytesize : data.size, data].pack('Na*')
end
end
end
end
37 changes: 37 additions & 0 deletions tests/test_object_protocol.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
$:.unshift "../lib"
require 'eventmachine'
require 'test/unit'

class TestObjectProtocol < Test::Unit::TestCase
Host = "127.0.0.1"
Port = 9550

module Server
include EM::P::ObjectProtocol
def post_init
send_object :hello=>'world'
end
def receive_object obj
$server = obj
EM.stop
end
end

module Client
include EM::P::ObjectProtocol
def receive_object obj
$client = obj
send_object 'you_said'=>obj
end
end

def test_send_receive
EM.run{
EM.start_server Host, Port, Server
EM.connect Host, Port, Client
}

assert($client == {:hello=>'world'})
assert($server == {'you_said'=>{:hello=>'world'}})
end
end

0 comments on commit ae7cf7c

Please sign in to comment.