javascript - Rails ActionController::Live - 立即发送所有内容而不是异步发送

标签 javascript ruby-on-rails ffmpeg server-sent-events actioncontroller

我有一个关于 Rails ActionController::Live 的问题

最后我想向用户展示 FFMPEG 的进展,但现在我想让这个最小的示例运行:

Rails media_controller.rb:

class MediaController < ApplicationController
  include ActionController::Live

  def stream
    puts "stream function loaded"

      response.headers['Content-Type'] = 'text/event-stream'
      i = 0
      begin
        response.stream.write "data: 1\n\n"
        sleep 0.5
        i += 1
        puts "response... data: " + i.to_s
      end while i < 10
    response.stream.close
  end
end

Javascript:

source = new EventSource("/test/0");
source.addEventListener("message", function(response) {
  // Do something with response.data
  console.log('I have received a response from the server: ' + response);
}, false);

当我导航到该网站时,没有显示 JavaScript 错误。一旦我导航到该站点,MediaController 的“stream”操作就会成功调用。我可以通过查看服务器控制台来验证这一点。它给了我以下输出。在每个响应行之后,都会有 500 毫秒的延迟,如预期的那样:

stream function loaded
response... data: 1
response... data: 2
response... data: 3
response... data: 4
response... data: 5
response... data: 6
response... data: 7
response... data: 8
response... data: 9
response... data: 10
Completed 200 OK in 5005ms (ActiveRecord: 0.8ms)

在 JavaScript 方面,它给出了以下输出:

(10x) I have received a response from the server: [object MessageEvent]

但问题就在这里,它在 5 秒后同时从服务器发送了所有这 10 条消息!然而,预期的行为是,它应该每 0.5 秒向我发送 1 条消息!

那么我在这里做错了什么?错误在哪里?

Screenshot Rails Console / JavaScript Console

最佳答案

我可以通过使用不同的网络服务器来解决该问题。之前我用过 thin,我发现了这个 Post on SO :

you can't use AC::Live with Thin

可以在此处找到说明:

https://github.com/macournoyer/thin/issues/254#issuecomment-67494889

Thin doesn't work with streaming and ActionController::Live.

The only approach that works with Thin is to use the async API: https://github.com/macournoyer/thin_async. Thin is built exactly for this kind of stuff and making it scale.

Or simpler, use this: https://github.com/SamSaffron/message_bus.

因此切换到另一台服务器解决了问题:

gem 'puma'

开始
rails s Puma

关于javascript - Rails ActionController::Live - 立即发送所有内容而不是异步发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35057075/

相关文章:

javascript - RegExp - 如何检查字符串中的两个括号

javascript - 查找 JSON 值是否包含特定文本

javascript - 允许用户在 window.open() 中更改 URL

android - C编译器错误: build ffmpeg for android

ffmpeg - 编译 libx264 时出错 : Undefined symbols for architecture x86_64

javascript - 错误: concatUint8Array: Data must be in the form of a Uint8Array

ruby-on-rails - 为什么我的线程变量在 Rails 中是断断续续的?

css - 将 Chartkick 折线图设置为正方形

ruby-on-rails - rails : How to make strong parameters easy to read

ffmpeg - ffmpeg Makefile 中的 "all-yes"是什么意思