The new ActionController::Live module provides the ability to stream data to clients. Simply include the module into a controller to enable your app to send arbitrary streamed data. You'll have to use a threaded server, like thin and puma, in order to stream data; actions from streaming controllers run in a separate thread.
Here's an example from the Rails 4 documentation:
Here's an example from the Rails 4 documentation:
class
MyController < ActionController::Base
include ActionController::Live
def
stream
response.headers[
'Content-Type'
] =
'text/event-stream'
100
.times {
response.stream.write
"hello world\n"
sleep
1
}
response.stream.close
end
end
As the docs note, there are three things to keep in mind:
- You must write any headers before you call write or close on the response stream.
- You have to call close on the response stream when you're finished writing data.
- Ensure that your actions are thread-safe, as they will run in a separate thread.
No comments:
Post a Comment