Skip to content

Instantly share code, notes, and snippets.

@tmm1
Created March 22, 2009 09:30
Show Gist options
  • Select an option

  • Save tmm1/83121 to your computer and use it in GitHub Desktop.

Select an option

Save tmm1/83121 to your computer and use it in GitHub Desktop.
possible EM::Socket api
# simple Socket API
module EventMachine
class Socket
class Client < EM::Connection
def initialize socket
@socket = socket
end
attr_accessor :socket
def connection_completed
socket.on(:connect)
end
def receive_data data
socket.on(:data, data)
end
def unbind
socket.on(:disconnect)
end
end
def initialize host, port = nil
@callbacks = {}
@connection = EM.connect host, port, Client, self
yield self if block_given?
end
def on type, *args, &blk
if blk
@callbacks[type] = blk
self
else
@callbacks[type] and @callbacks[type].call(*args)
end
end
def send data
@connection.send_data data
end
def disconnect flush_data = true
@connection.close_connection(flush_data)
end
end
end
if __FILE__ == $0
module EchoServer
def receive_data data
send_data ">> #{data}"
end
end
EM.start_server 'localhost', 8081, EchoServer
EM.start_server '/tmp/echoserver.sock', EchoServer
EM.describe EM::Socket do
{ 'TCP' => ['localhost', 8081],
'Unix Domain' => '/tmp/echoserver.sock'
}.each{|type, url|
should "connect to #{type} servers" do
incoming = nil
EM::Socket.new(*url) do |s|
s.on(:connect){
s.send "hi from #{type}"
}.on(:data){ |data|
data.should == ">> hi from #{type}"
s.disconnect
}.on(:disconnect){
done
}
end
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment