-
-
Save aymerick/83155 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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