【问题标题】:Rails ActionController::Live - Sends everything at once instead of asyncRails ActionController::Live - 一次发送所有内容而不是异步
【发布时间】:2016-05-05 13:38:10
【问题描述】:

我对 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 的“流”-Action 就会成功调用。我可以通过查看服务器控制台来验证这一点。它给了我以下输出。在每个响应行之后,都会有 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 条消息!

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

【问题讨论】:

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


    【解决方案1】:

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

    您不能将AC::LiveThin 一起使用

    可以在这里找到解释:

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

    Thin 不适用于流式传输和 ActionController::Live。

    与 Thin 一起使用的唯一方法是使用异步 API: https://github.com/macournoyer/thin_async。 Thin 正是为这类东西而构建的,并使其可扩展。

    或者更简单,使用这个:https://github.com/SamSaffron/message_bus

    所以切换到另一个服务器解决了这个问题:

    gem 'puma'
    

    开始
    rails s Puma
    

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 2015-01-25
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多