0

我正在开发一个流媒体服务器,它使用Goliath和 SSE 实时发送最新推文、新闻 ets 等更新。该服务器将映射到不同的域。

索引.html

<script>
    if(typeof(EventSource)!=="undefined") {
        var source = new EventSource('http://192.168.0.44:9000/api/stream/articles?channel=Headlines');

        // new connection opened callback
        source.addEventListener('open', function(e) {
          console.log('connection opened');
        }, false);

        // new connection opened callback
        source.addEventListener('message', function(e) {
            console.log(e.data);
           msg = JSON.parse(e.data);
           $('#result').append('<br/>').append(msg);
        }, false);

        // connection closed callback
        source.addEventListener('error', function(e) {
          if (e.eventPhase == EventSource.CLOSED) {
            console.log('connection closed');
          }
        }, false);
    } else {
        $('#result').append('<br/>').append("Whoops! Your browser doesn't receive server-sent events.") ;
    }
  </script>

歌利亚组件

#!/usr/bin/env ruby
require 'rubygems'
require 'goliath'

class RedisPubsub < Goliath::API
  use(Rack::Static, :root => Goliath::Application.app_path("public"), :urls => ["/index.html", "/twitter.html", "/favicon.ico", '/stylesheets/', '/javascripts/', '/images/'])
  use Goliath::Rack::Params
  use Goliath::Rack::Render, 'json'

  def response(env)
    ...
    ....
    env.stream_send("data:#{message}\n\n")
    streaming_response(200, {'Content-Type' => 'text/event-stream', 'Access-Control-Allow-Origin' => '*'})
  end
end

Goliath 流媒体服务器在本地机器的 9000 端口上运行。当我尝试通过http://localhost/index.html它访问页面时,即使它发送 CORS 'Access-Control-Allow-Origin' 标头作为响应,也会给出 Chrome 中提到的错误。请不要在这里它在FF上工作正常。

知道如何解决这个问题吗?

4

1 回答 1

0

您需要将 Content-type 标头设置为 text/event-stream,如http://www.html5rocks.com/en/tutorials/eventsource/basics/中所示。

于 2012-12-06T04:55:30.423 回答