28Mar/100
Ruby chat-server with Fibers & Eventmachine
Posting this mostly for my reference so I don't lose it again later.
require 'rubygems'
require 'eventmachine'
class Connection < EventMachine::Connection
attr_accessor :fiber, :name
def initialize
@fiber = Fiber.new { poll }
@name = nil
end
def post_init
(@@connections ||= []) << self
@fiber.resume
end
def poll
send_data( "What is your name?" )
@name = Fiber.yield
send_data( "OK, your name is #{@name}\n")
loop do
msg = Fiber.yield
@@connections.each do |conn|
conn.send_data( "#{@name} said: #{msg}\n")
end
end
end
def receive_data( data )
@fiber.resume data.strip
end
end
EventMachine.run do
EM.start_server "0.0.0.0", 2000, Connection
end