Created
August 28, 2009 04:29
-
-
Save dhotson/176785 to your computer and use it in GitHub Desktop.
This file contains 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' | |
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