класс ActionController::Live::SSE
Этот класс предоставляет возможность записи SSE (Server Sent Event) в поток IO. Класс инициализируется потоком и может использоваться для записи строки JSON или объекта, который можно преобразовать в JSON.
Запись объекта преобразует его в стандартный формат SSE с настроенными параметрами. Вы можете настроить следующие параметры:
1) Event. If specified, an event with this name will be dispatched on the browser. 2) Retry. The reconnection time in milliseconds used when attempting to send the event. 3) Id. If the connection dies while sending an SSE to the browser, then the server will receive a +Last-Event-ID+ header with value equal to +id+.
После установки параметра в конструкторе объекта SSE, все последующие SSE, отправленные через поток, будут использовать эти параметры, если не переопределены.
Пример использования:
class MyController < ActionController::Base
include ActionController::Live
def index
response.headers['Content-Type'] = 'text/event-stream'
sse = SSE.new(response.stream, retry: 300, event: "event-name")
sse.write({ name: 'John'})
sse.write({ name: 'John'}, id: 10)
sse.write({ name: 'John'}, id: 10, event: "other-event")
sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500)
ensure
sse.close
end
end
Примечание: SSE в настоящее время не поддерживаются IE. Однако они поддерживаются Chrome, Firefox, Opera и Safari.
Константы
- PERMITTED_OPTIONS
Публичные методы класса
# File actionpack/lib/action_controller/metal/live.rb, line 91
def initialize(stream, options = {})
@stream = stream
@options = options
end Публичные методы экземпляра
# File actionpack/lib/action_controller/metal/live.rb, line 96 def close @stream.close end
# File actionpack/lib/action_controller/metal/live.rb, line 100
def write(object, options = {})
case object
when String
perform_write(object, options)
else
perform_write(ActiveSupport::JSON.encode(object), options)
end
end
© 2004–2019 David Heinemeier Hansson
Licensed under the MIT License.