javascript - 使用 Ruby Grape 服务器发送的事件

标签 javascript ruby server-sent-events ruby-grape

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

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

这是我的 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 方法时,数据永远不会到达浏览器。

预先感谢您的回答。

最佳答案

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

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

关于javascript - 使用 Ruby Grape 服务器发送的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29393077/

相关文章:

javascript - 使用由于组件问题而无法正常工作的事件使用 Vue.js 上传图像

javascript - 如何处理 Codesandbox 上 React 应用程序中的错误 - "Failed to fetch"

javascript - 将 "Tag"(字符串)替换为 JavaScript 中的所有匹配项

ruby - 你推荐哪个 Ruby 的 Twitter API 库?

ruby - 在 Rspec 测试中运行 Rake 任务

c# - 未调用 OWIN web api CancellationToken

html - SSE 和 Servlet 3.0

javascript - 将返回值显示为文本

ruby - 如何简化这个正则表达式?

python - 如何将通知推送给特定的登录用户。我的代码如下所示