-
-
Save lisovskyvlad/9ccc1f2c03cb9f017a73 to your computer and use it in GitHub Desktop.
Rails 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 jquery | |
//= require jquery_ujs | |
$(function() { | |
var source = new EventSource('/stream'); | |
source.addEventListener('counter', function(e) { | |
$('body').after(e.data + '<br />'); | |
}); | |
}); |
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
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 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
- 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