class ActionController::Live::SSE
Chrome, Firefox, Opera, and Safari.
Note: SSEs are not currently supported by IE. However, they are supported by
end
end
sse.close
ensure
sse.write({ name: ‘John’}, id: 10, event: “other-event”, retry: 500)
sse.write({ name: ‘John’}, id: 10, event: “other-event”)
sse.write({ name: ‘John’}, id: 10)
sse.write({ name: ‘John’})
sse = SSE.new(response.stream, retry: 300, event: “event-name”)<br>response.headers = ‘text/event-stream’
def index
include ActionController::Live
class MyController < ActionController::Base
Example Usage:
sent across the stream will use those options unless overridden.
After setting an option in the constructor of the SSE object, all future SSEs
server will receive a ‘Last-Event-ID` header with value equal to `id`.
: If the connection dies while sending an SSE to the browser, then the
`:id`
: The reconnection time in milliseconds used when attempting to send the event.
`:retry`
: If specified, an event with this name will be dispatched on the browser.
`:event`
options you have configured. You may choose to set the following options:
Writing an object will convert it into standard SSE format with whatever
a JSON string or an object which can be converted to JSON.
stream. The class is initialized with a stream and can be used to either write
This class provides the ability to write an SSE (Server Sent Event) to an IO
# Action Controller Live Server Sent Events
def close
def close @stream.close end
def initialize(stream, options = {})
def initialize(stream, options = {}) @stream = stream @options = options end
def perform_write(json, options)
def perform_write(json, options) current_options = @options.merge(options).stringify_keys PERMITTED_OPTIONS.each do |option_name| if (option_value = current_options[option_name]) @stream.write "#{option_name}: #{option_value}\n" end end message = json.gsub("\n", "\ndata: ") @stream.write "data: #{message}\n\n" end
def write(object, options = {})
def write(object, options = {}) case object when String perform_write(object, options) else perform_write(ActiveSupport::JSON.encode(object), options) end end