【问题标题】:EventSource error on each connection close每次连接关闭时的 EventSource 错误
【发布时间】:2020-12-27 01:19:44
【问题描述】:

在 PoC 应用程序上使用 Rails+SSE 进行实验时,我遇到了一个奇怪的行为。消息成功发送到JS,但同时调用了error handler:

我有带有以下控制器的 Rails 6:

class UsersController < ApplicationController
  include ActionController::Live

  def index_stream
    # SSE expects the `text/event-stream` content type
    response.headers['Content-Type'] = 'text/event-stream'

    # last_updated = User.last_updated.first
    sse = SSE.new(response.stream)
    sse.write(name: 'John')
  ensure
    sse.close
  end
end

config.allow_concurrency = truedevelopment.rb。使用puma 作为网络服务器。

JS代码:

var source = new EventSource('/user_stream');

source.onmessage = function(e) {
  console.log('Message: ', e);
  document.getElementById('users').append(e.data);
};

source.onerror = function(e) {
  console.log('Error:', e);
};

响应标头:

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
ETag: W/"566367df563a9487c3b0707958010517"
Set-Cookie: _sse_demo_session=WOvy%2Bknjwq%2FZzuDQQl5lTRV96Glvhe%2FdGCaIkkokzGZNpIdobigxIyVaIozYMnY70aB9RcH2muN11xPE0r%2BZ%2F8E95m9sGMNKMyu4LgVC%2BtH1b8FxHHqSkuLA0QIoc4M3VfxWjLZkSrSg9OL5edo2kKGnW0x2R70itcwvq5d62RE%2BzQHSFHT%2FBF%2F32zWb%2FgO9e1mkgI%2FFoz33c6x6zI1QftTxTe7eeFQ0CAlEDBJsTmBQ2xo8yZBlOzn0uqe66LENld1bANvCoYxTXFxZTeyWW46uv7x5lihywA%3D%3D--pgfHW6WrLuKnKnAF--idzmcsiSA8CS85mu4a4QsA%3D%3D; path=/; HttpOnly
X-Request-Id: 0e17b656-04d7-4c63-9ca4-d8650d0ccf96
X-Runtime: 0.028097
Transfer-Encoding: chunked

任何想法为什么会引发错误?可以在GitHubHeroku 上找到演示应用程序

【问题讨论】:

    标签: ruby-on-rails server-sent-events puma


    【解决方案1】:

    我自己找到了答案。根据W3C spec,这是正常行为:

    当用户代理要重新建立连接时,用户代理必须运行以下步骤。这些步骤是异步运行的,而不是作为任务的一部分。 (当然,它排队的任务像普通任务一样运行,而不是异步运行。) 排队任务以运行以下步骤:

    1. 如果 readyState 属性设置为 CLOSED,则中止任务。
    2. 将 readyState 属性设置为 CONNECTING。
    3. 在 EventSource 对象上触发一个名为 error 的简单事件。

    所以,它就是这样一个协议。

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 2020-06-04
      • 2017-01-12
      • 2019-06-29
      • 1970-01-01
      • 2018-07-11
      相关资源
      最近更新 更多