Created
August 4, 2012 19:28
-
-
Save lexmag/3259481 to your computer and use it in GitHub Desktop.
Rails streaming
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 jquery | |
//= require jquery_ujs | |
$(function() { | |
var source = new EventSource('/stream'); | |
source.addEventListener('counter', function(e) { | |
$('body').after(e.data + '<br />'); | |
}); | |
}); |
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
class PostsController < ApplicationController | |
# ... | |
def stream | |
response.headers.delete('Content-Length') | |
response.headers['Cache-Control'] = 'no-cache' | |
response.headers['Content-Type'] = 'text/event-stream' | |
self.response_body = Enumerator.new do |y| | |
loop do | |
if (Time.current.sec % 5).zero? | |
y << "event: counter\n" | |
y << "data: 5 seconds passed\n\n" | |
end | |
sleep 1 | |
end | |
end | |
end | |
# The new approach | |
# include ActionController::Live | |
def stream | |
response.headers['Content-Type'] = 'text/event-stream' | |
begin | |
loop do | |
if (Time.current.sec % 5).zero? | |
response.stream.write("event: counter\n") | |
response.stream.write("data: 5 seconds passed\n\n") | |
end | |
sleep 1 | |
end | |
rescue IOError | |
# Catch when the client disconnects | |
ensure | |
response.stream.close | |
end | |
end | |
# ... | |
end |
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
- close stream | |
- IE has not server-sent events | |
- preload_frameworks & allow_concurrency options in development | |
- Puma, Thin, Rainbow! servers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not works with thin by default. (Rails 4.2.3 / MRI 2.1.2 / Thin 1.6.3)
Thin has 3 years old "streaming" branch, which was not merged to master https://github.com/macournoyer/thin/tree/streaming
Another solution https://groups.google.com/d/msg/thin-ruby/R2L4-FG5ZfY/x4cWnl7w6RMJ