Created
January 20, 2012 17:35
-
-
Save jfairbairn/1648593 to your computer and use it in GitHub Desktop.
An eventmachine-based test server forking child processes to do the work, connecting to a UNIX domain socket on which the parent process is listening.
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
require 'eventmachine' | |
CRLF = "\r\n" | |
module Child | |
attr_writer :child_number | |
include EM::P::LineText2 | |
def post_init | |
set_line_mode | |
end | |
def receive_line(line) | |
send_data "#{@child_number}: #{line}#{CRLF}" | |
end | |
end | |
CHILD_CONNS = [] | |
OUTSIDE_CONNS = [] | |
module ConnectionToChild | |
include EM::P::LineText2 | |
def post_init | |
CHILD_CONNS << self | |
end | |
def unbind | |
CHILD_CONNS.delete self | |
end | |
def receive_line(line) | |
OUTSIDE_CONNS.each do |conn| | |
conn.send_data(line) | |
conn.send_data(CRLF) | |
end | |
end | |
end | |
module OutsideServer | |
include EM::P::LineText2 | |
def post_init | |
@child_num = 0 | |
OUTSIDE_CONNS << self | |
end | |
def unbind | |
OUTSIDE_CONNS.delete self | |
end | |
def receive_line(line) | |
child = CHILD_CONNS[@child_num] | |
@child_num = (@child_num + 1) % CHILD_CONNS.size | |
if child.nil? | |
STDERR.puts("no children connected!") | |
else | |
child.send_data(line) | |
child.send_data(CRLF) | |
end | |
end | |
end | |
UDS_PATH = "robin_sock.sock" | |
EM.run do | |
EM.start_server("0.0.0.0", 10000, OutsideServer) | |
EM.start_server(UDS_PATH, ConnectionToChild) | |
4.times do |i| | |
EM.fork_reactor do | |
EM.connect(UDS_PATH, Child) do |conn| | |
conn.child_number = i | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Amazing :) Can be a nice common pattern, actually :) +1