2014-03-27 47 views
0

我想使用與rails 4一起引入的實時流式傳輸功能。在我的應用程序中,它不起作用,所以我創建了一個非常簡單的示例。但是這也不會流式傳輸內容。它打開連接,等到所有10次運行都已經過去,然後傳輸競爭。Rails Live Streaming不會流式傳輸

以下是示例代碼。

  • 首先,我創建了軌道新的Rails應用程序4.0.2
  • 其次,我添加寶石「彪馬」,使流媒體直播支持

控制器看起來像這樣:

class MyController < ApplicationController 
include ActionController::Live 

def index 
    response.headers['Content-Type'] = 'text/event-stream' 
     10.times { 
      response.stream.write "This is a test Messagen" 
      sleep 1 
     } 
     response.stream.close 
    end 
end 

我用捲曲來進行測試:

curl -i http://localhost:3000/my 
HTTP/1.1 200 OK 
X-Frame-Options: SAMEORIGIN 
X-XSS-Protection: 1; mode=block 
X-Content-Type-Options: nosniff 
X-UA-Compatible: chrome=1 
Content-Type: text/event-stream 
Cache-Control: no-cache 
Set-Cookie: request_method=GET; path=/ 
X-Request-Id: 7bdf30a2-158b-40ce-81c8-651914c7b5df 
X-Runtime: 0.048783 
Transfer-Encoding: chunked 

This is a test MessagenThis is a test MessagenThis is a test MessagenThis is a test 
MessagenThis is a test MessagenThis is a test MessagenThis is a test MessagenThis is a test 
MessagenThis is a test MessagenThis is a test Messagen 

但它持續10秒,直到消息全部寫在一起(不是每秒一次)。

我在互聯網上的很多頁面上發現了這個代碼示例 - 但不知道出了什麼問題。

任何想法?

+0

我發現,這是第三方問題。使用influxdb-rails「銷燬」實時流式傳輸功能。他們爲我解決了這個問題。 – PascalTurbo

回答

0

首先,我相信你需要一個換行符才能使它捲曲。

response.stream.write "This is a test Messagen\n" 

curl localhost:3000 

This is a test Messagen 
This is a test Messagen 
This is a test Messagen 
This is a test Messagen 
This is a test Messagen 

的換行符(\ n)似乎允許流逐步與睡眠,而不是發生的等待時間的整個塊,然後立刻吐出的結果。

對於實際渲染到一個視圖(EventSource的),你將需要設置

config.cache_classes = true 
config.eager_load = true 

這將工作「OK」了一個Hello World,但東西是固體和可擴展的我會去的Redis而不是在您最終從數據庫中提取時循環。