Skip to content

Instantly share code, notes, and snippets.

@fanktom
Created May 24, 2012 11:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanktom/2780900 to your computer and use it in GitHub Desktop.
Save fanktom/2780900 to your computer and use it in GitHub Desktop.
Ruby Server Side Events Server implementation with Goliath
require 'goliath'
require 'em-synchrony/em-http'
# After a connect the server streams 10 bomb ticks and then stops with a BOOM. The
# event source needs to listen to source.addEventListener 'bomb', .. to retrieve
# the ticks.
class Stream < Goliath::API
def response(env)
i = 0
# Tick every second until the boom
bomb_timer = EM.add_periodic_timer(1) do
env.stream_send "event: bomb\n"
env.stream_send("data: #{i}\n\n")
i += 1
end
# Cancel bomb timer after 10 seconds with a BOOM
EM.add_timer(10) do
bomb_timer.cancel
env.stream_send "event: bomb\n"
env.stream_send("data: !! BOOM !!\n\n")
end
# Stream response to client
streaming_response(200, {'Content-Type' => 'text/event-stream', 'Cache-Control' => 'no-cache', 'Connection' => 'keep-alive'})
end
end
# As the client and server must follow the same origin rule, the proxy simply
# redirects all requests not "/stream" to another server that e.g. hosts the
# javascript with the EventSource code. Feel free to adapt the proxy destination
# to your needs
class Proxy < Goliath::API
def response(env)
url = "http://localhost:9292#{env['REQUEST_PATH']}?#{env['QUERY_STRING']}"
logger.info "Proxying #{url}"
http = EM::HttpRequest.new(url).get
[http.response_header.status, {'Content-Type' => http.response_header["CONTENT_TYPE"] }, http.response]
end
end
# Maps the requests to stream to the Server Side Events stream, and sends everything
# else to the proxy
class Routes < Goliath::API
get "/stream" , Stream
not_found "/" do run Proxy.new end
end
# Start with: ruby server_side_events_server.rb -sv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment