-
-
Save jeremyvdw/1175380 to your computer and use it in GitHub Desktop.
HTML5 SSE / EventSource demo with Goliath
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
source :gemcutter | |
gem 'goliath', :git => 'git://github.com/postrank-labs/goliath.git' | |
gem 'em-synchrony', :git => 'git://github.com/igrigorik/em-synchrony.git' |
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
<!DOCTYPE html> | |
<html> | |
<body> | |
<h3>Hello SSE!</h3> | |
<script> | |
var source = new EventSource('/events'); | |
// new connection opened callback | |
source.addEventListener('open', function(e) { | |
console.log('connection opened'); | |
}, false); | |
// subscribe to unnamed messages | |
source.onmessage = function(e) { | |
console.log(e); | |
document.body.innerHTML += e.data + '<br />'; | |
}; | |
// listen for signup events | |
source.addEventListener('signup', function(e) { | |
console.log(e); | |
document.body.innerHTML += e.data + '<br />'; | |
}, false); | |
// connection closed callback | |
source.addEventListener('error', function(e) { | |
if (e.eventPhase == EventSource.CLOSED) { | |
console.log('connection closed'); | |
} | |
}, false); | |
</script> | |
</body> | |
</html> |
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
web: bundle exec ruby sse.rb -sv -e prod -p $PORT |
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 'goliath' | |
class EventGenerator < Goliath::API | |
def response(env) | |
EM.add_periodic_timer(1) { env.stream_send("data:hello ##{rand(100)}\n\n") } | |
EM.add_periodic_timer(3) do | |
env.stream_send(["event:signup", "data:signup event ##{rand(100)}\n\n"].join("\n")) | |
end | |
streaming_response(200, {'Content-Type' => 'text/event-stream'}) | |
end | |
end | |
class SSE < Goliath::API | |
use Rack::Static, :urls => ["/index.html"], :root => Goliath::Application.app_path("public") | |
get "/events" do | |
run EventGenerator.new | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment