[英]Rails ActionController::Live - Sends everything at once instead of async
我在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” -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條消息!
那我在做什么錯呢? 錯誤在哪里?
我可以通過使用其他Web服務器來解決此問題。 以前我使用thin
並且在SO上找到了這篇文章 :
您不能使用
AC::Live
withThin
可以在這里找到說明:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.