每个连接关闭时的EventSource错误

时间:2020-09-08 15:58:15

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

在PoC应用程序上使用Rails + SSE进行实验我遇到了奇怪的问题。该消息已成功发送到JS,但同时调用了error处理程序:

Google Chrome Web Inspector Console

我有带有以下控制器的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 = true for development.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

上找到演示应用

1 个答案:

答案 0 :(得分:0)

独自找到答案。根据{{​​3}},这是正常现象:

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

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

所以,就是这样的协议。

相关问题