класс ActionController::Live::SSE
Этот класс предоставляет возможность записи SSE (события, отправляемые сервером) в поток ввода-вывода. Класс инициализируется потоком и может использоваться для записи строковой записи 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.
Постоянные
- WHITELISTED_OPTIONS
Публичные методы класса
# File actionpack/lib/action_controller/metal/live.rb, line 89
def initialize(stream, options = {})
@stream = stream
@options = options
end Публичные методы экземпляра
# File actionpack/lib/action_controller/metal/live.rb, line 94 def close @stream.close end
# File actionpack/lib/action_controller/metal/live.rb, line 98
def write(object, options = {})
case object
when String
perform_write(object, options)
else
perform_write(ActiveSupport::JSON.encode(object), options)
end
end
© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.