gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:26:48 25 4
gpt4 key购买 nike

我有一个关于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com