Skip to content

Instantly share code, notes, and snippets.

@lexmag
Created August 4, 2012 19:28
Show Gist options
  • Save lexmag/3259481 to your computer and use it in GitHub Desktop.
Save lexmag/3259481 to your computer and use it in GitHub Desktop.
Rails streaming
//= require jquery
//= require jquery_ujs
$(function() {
var source = new EventSource('/stream');
source.addEventListener('counter', function(e) {
$('body').after(e.data + '<br />');
});
});
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
- close stream
- IE has not server-sent events
- preload_frameworks & allow_concurrency options in development
- Puma, Thin, Rainbow! servers
@x2es
Copy link

x2es commented Sep 5, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment