Created
August 4, 2012 22:32
-
-
Save lexmag/3260374 to your computer and use it in GitHub Desktop.
Terribly simple Sinatra streaming
This file contains hidden or 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 'sinatra' | |
set server: :thin | |
get '/' do | |
erb :welcome | |
end | |
get '/stream', provides: 'text/event-stream' do | |
stream do |out| | |
loop do | |
if (Time.now.sec % 5).zero? | |
out << "event: counter\n" | |
out << "data: 5 seconds passed\n\n" | |
end | |
sleep 1 | |
end | |
end | |
end | |
__END__ | |
@@ layout | |
<html> | |
<head> | |
<title>Terribly simple streaming with Sinatra</title> | |
<meta charset='utf-8' /> | |
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script> | |
<script> | |
var source = new EventSource('/stream'); | |
source.addEventListener('counter', function(e) { $('#counter').append(e.data + '<br />') }); | |
</script> | |
</head> | |
<body><%= yield %></body> | |
</html> | |
@@ welcome | |
<div id='counter'></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment