Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

HTML5 SSE / EventSource demo with Goliath

View Gemfile
1 2 3 4
source :gemcutter
 
gem 'goliath', :git => 'git://github.com/postrank-labs/goliath.git'
gem 'em-synchrony', :git => 'git://github.com/igrigorik/em-synchrony.git'
View Gemfile
1
web: bundle exec ruby sse.rb -sv -e prod -p $PORT
View Gemfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
<!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>
View Gemfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14
require 'goliath'
 
class SSE < Goliath::API
use Rack::Static, :urls => ["/index.html"], :root => Goliath::Application.app_path("public")
 
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

@igrigorik should index.html be under public/ ? I wanted to run the example locally, had to add public and then move index there.

Owner

Yep, just create public directory and it should do the trick

Looks like something went wrong:

sse.rb:17:in class:SSE': undefined methodget' for SSE:Class (NoMethodError)
from sse.rb:14:in `'

If you know the fix, I'll be very much obliged. Thank you.

@danielsz With the release of Goliath 1.0, the router has been extracted to its own gem: https://github.com/postrank-labs/goliath/issues/143

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.