Rails Streaming不流式传输

我正在努力为我的rails应用程序添加一个流组件,因为我想开始使用SSE。 我试过让它在一个较小的例子中工作,但我仍然遇到麻烦。 我一直无法实际获取rails以正确地传递对curl请求的响应。 我正在关注http://tenderlovemaking.com/2012/07/30/is-it-live.html上的教程。 我不确定是否有必要为OSX配置的东西,或者我的配置中是否缺少某些东西。 任何帮助将不胜感激。

我在OSX本地运行它。 当我运行curl -i localhost:3000我得到以下响应:

 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 Last-Modified: Wed Apr 23 23:10:15 2014 Cache-Control: no-cache Set-Cookie: request_method=GET; path=/ X-Request-Id: 89f2af3e-76e9-4873-85b0-3b6fe45f6343 X-Runtime: 0.001724 Transfer-Encoding: chunked hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world 

问题是我得到了所有这一切,而不是像预期的那样得到响应的位。 如果我需要提供更多信息,请告诉我

我的代码如下:

stream_test_controller.rb

 class StreamTestController < ActionController::Base include ActionController::Live def index response.headers['Content-Type'] = 'text/event-stream' 10.times { logger.info "hello world sent" response.stream.write "hello world\n" sleep 1 } response.stream.close end end 

的Gemfile

 source 'https://rubygems.org' ruby '2.1.0' gem 'rails', '4.0.3' gem 'sqlite3' gem 'sass-rails', '~> 4.0.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 1.2' gem 'puma' group :doc do gem 'sdoc', require: false end 

development.rb

 StreamTest::Application.configure do config.preload_frameworks = true config.allow_concurrency = true # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = true # Do not eager load code on boot. config.eager_load = true # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true end 

从这里的文档中 ,您使用WEBrick进行测试吗?

WEBrick服务器缓冲所有响应,因此包括ActionController :: Live将无法正常工作。 您必须使用不会自动缓冲响应的Web服务器。

尝试在curl命令中禁用缓冲。 从联机帮助页:

-N, – no-buffer

禁用输出流的缓冲。 在正常工作情况下,curl将使用标准缓冲输出流,这将产生以块为单位输出数据的效果,而不一定是数据到达时。 使用此选项将禁用该缓冲。

SSE消息由两个换行符( 链接 )分隔。

你的代码应该有:

 response.stream.write "hello world\n\n"