Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Created August 18, 2012 23:42
Show Gist options
  • Save kwilczynski/3390373 to your computer and use it in GitHub Desktop.
Save kwilczynski/3390373 to your computer and use it in GitHub Desktop.
EventMachine example
krzysztof@samsung:~$ socat unix-connect:/tmp/test.sock stdin
This is a test.
krzysztof@samsung:~$ socat unix-connect:/tmp/test.sock stdin
This is also a test.
krzysztof@samsung:~$
krzysztof@samsung:~$ ruby em-test.rb
I, [2012-08-19T00:39:55.485256 #22753] INFO -- : Got: This is a test.
I, [2012-08-19T00:40:02.388188 #22753] INFO -- : Got: This is also a test.
^C
krzysztof@samsung:~$
#!/usr/bin/env ruby
require 'logger'
begin
require 'eventmachine'
rescue LoadError
require 'rubygems'
require 'eventmachine'
end
module Test
class Server
class << self
def channel
@@channel ||= EventMachine::Channel.new
end
end
def initialize(socket_path, options={})
@socket_path = socket_path
@channel = Test::Server.channel
@log = Logger.new(STDOUT)
@log.level = Logger::DEBUG
end
def start
@channel.subscribe {|data| process_incoming_data(data) }
EventMachine.run do
EventMachine.start_unix_domain_server(@socket_path, Server::Connection)
end
end
def stop
EventMachine.next_tick { EventMachine.stop rescue nil }
end
private
def process_incoming_data(data)
@log.info("Got: #{data.strip}")
end
class Connection < EventMachine::Connection
def initialize
super
@channel = Test::Server.channel
end
def receive_data(data)
@channel.push(data)
close_connection
end
end
end
end
if $0 == __FILE__
ts = Test::Server.new('/tmp/test.sock')
Kernel.trap('INT') { ts.stop }
ts.start
end
# vim: set ts=2 sw=2 et :
# encoding: utf-8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment