Skip to content

Instantly share code, notes, and snippets.

@dhotson
Created August 28, 2009 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhotson/176785 to your computer and use it in GitHub Desktop.
Save dhotson/176785 to your computer and use it in GitHub Desktop.
require 'eventmachine'
EM.run do
EM.epoll
# Create a channel to push data to
EventChannel = EM::Channel.new
# The server simply subscribes client connections to the channel on connect,
# and unsubscribes them on disconnect.
class Server < EM::Connection
def self.start(host = '0.0.0.0', port = 8000)
EM.start_server(host, port, self)
end
def post_init
send_data "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: text/html\r\n\r\n"
send_chunk "<html><body>";
@sid = EventChannel.subscribe do |m|
send_chunk "#{m.strip}<br />"
end
end
def send_chunk c
send_data (c.length.to_s(16)+"\r\n"+c+"\r\n")
end
def unbind
EventChannel.unsubscribe @sid
end
end
Server.start
# This server recieves events to broadcast to channel subscribers
class EventListener < EM::Connection
def self.start(host = '0.0.0.0', port = 8001)
EM.start_server(host, port, self)
end
def receive_data(data)
EventChannel << data
end
end
EventListener.start
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment