【问题标题】:Server-Sent Events with Ruby Grape使用 Ruby Grape 的服务器发送事件
【发布时间】:2015-04-01 14:11:43
【问题描述】:

我正在尝试在我的Ruby Grape API 上创建服务器发送事件。 问题是连接似乎一直很快就关闭了,因为我在测试网页上一直收到Connection closed 事件。

客户端连接到服务器,因为我可以看到正在调用的方法,但我想知道为什么连接不是恒定的以及为什么我没有收到使用线程发送的数据。

这是我的 Ruby 代码:

$connections = []

class EventsAPI < Sinantra::Base

  def connections
    $connections
  end

  get "/" do
    content_type "text/event-stream"
    stream(:keep_open) { |out|
      puts "New connection"
      out << "data: {}\n\n"
      connections << out
    }
  end

  post "/" do
    data = "data\n\n"
    connections.each { |out| out << data }
    puts "sent\n"
  end

end

这是我的 Javascript:

  var source = new EventSource('http://localhost:9292/events');

  source.onmessage = function(e) {
      console.log("New message: ", e.data);
      showMessage(e.data);
  };

  source.onopen = function(e) {
      // Connection was opened.
  };

  source.onerror = function(e) {
      console.log("Source Error", e)
      if (e.eventPhase == EventSource.CLOSED) {
          console.log("Connection was closed");
          // Connection was closed.
      }
  };

  var showMessage = function(msg) {
      var out = document.getElementById('stream');
      var d = document.createElement('div')
      var b = document.createElement('strong')
      var now = new Date;
      b.innerHTML = msg;
      d.innerHTML = now.getHours() + ":" + now.getMinutes() + ":" +now.getSeconds() + "  ";
      d.appendChild(b);
      out.appendChild(d);
  };

编辑:我使用 GET 方法得到了它(我将 Grape::API 更改为 Sinatra::Base,因为 Grape 没有实现流)。我现在收到数据,但连接没有保持活动状态,当我使用 post 方法时,数据永远不会到达浏览器。

提前感谢您的回答。

【问题讨论】:

  • 我刚刚回答了,但如果您正在关注 Grape API 中专门针对 SSE 的示例,则发布指向该文档的链接会很有用。 (特别是我想知道 :keep_open 到底做了什么。)

标签: javascript ruby server-sent-events grape


【解决方案1】:

JS 代码看起来是正确的。我的猜测是你不应该为你的无限循环启动一个新线程。将会发生的是,主线程将继续执行,到达其块的末尾,并关闭 http 请求。然后,您的分离线程将写入一个不存在的 out 流。

更新以响应您的编辑: SSE 不支持 POST。只能使用 GET 数据或 cookie 将数据传递给 SSE 进程。

【讨论】:

  • 我删除了循环和线程只是为了确保我得到数据。它可以工作(见上文),但连接不会保持活动状态。
  • 您需要无限循环:一旦您的进程结束,SSE 连接就会关闭。
猜你喜欢
  • 2011-07-10
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 2020-06-20
  • 2013-05-01
  • 2015-09-24
  • 2015-06-16
  • 2013-08-20
相关资源
最近更新 更多