2014-03-27 41 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而不是在您最终从数据库中提取时循环。