通过Cramp(Ruby)和SSE(HTML5)实时更新

时间:2012-10-25 08:12:10

标签: ruby html5 ruby-on-rails-3 server-sent-events cramp

我准备了一个示例应用程序,使用Cramp(Ruby)SSE(HTML5)实时从服务器获取更新。

通过http://localhost/sse_time.html

访问html时出现以下错误
Errors:
Chrome:
  Uncaught Error: SECURITY_ERR: DOM Exception 18 sse_time.html:9
  Uncaught TypeError: Cannot read property 'key-preview' of undefined 

Firefox:
  Error: The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
Line: 0

  Error: The connection to http://localhost:3000/time was interrupted while the page was loading.
  Line: 9

sse_time.html

<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
  if (!!window.EventSource) {

    var source = new EventSource('http://localhost:3000/time');

    source.addEventListener('message', function(e) {
      console.log(e.data);
    }, false);

    source.addEventListener('open', function(e) {
      // Connection was opened.
      console.log('Connection was opened.');
    }, false);

    source.addEventListener('error', function(e) {
      if (e.readyState == EventSource.CLOSED) {
        // Connection was closed.
        console.log('Connection was closed.');
      }
    }, false);

  } else {
    document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
  }
</script>

</body>
</html>

应用/动作/ time_action.rb

class TimeAction < Cramp::Action
  self.transport = :sse

  periodic_timer :send_latest_time, every: 5

  def send_latest_time
    render "Current time : #{Time.now}"
  end
end

其中line 9var source = new EventSource('http://localhost:3000/time');

如果我在Chrome中点击http://localhost:3000/time,它会在每5秒后显示一段时间而没有任何错误。

但是使用PHP代码,可以在http://localhost:3000/time

中用stream.php替换URI sse_time.html

stream.php

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.

/**
 * Constructs the SSE data format and flushes that data to the client.
 *
 * @param string $id Timestamp/id of this connection.
 * @param string $msg Line of text that should be transmitted.
 */
function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}

$serverTime = time();

sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));

此处stream.phpsse_time.html位于同一位置。

有人可以指导我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

参考CASE STUDY: REAL-TIME UPDATES IN STREAM CONGRESS

  

要记住EventSource的一个重要问题是不允许跨域连接。这意味着必须从与主Rails应用程序相同的streamcongress.com域提供Cramp应用程序。

我意识到html页面也需要成为抽筋应用程序的一部分(尽管有替代方案)。所以我进行了以下更改并且有效。

基于Cramp chat using Redis Pub/Sub + WebSockets修改app/actions/home_action.rb

class HomeAction < Cramp::Action
  @@template = ERB.new(File.read(PocRailsCramp::Application.root('app/views/index.html.erb')))

  def start
    render @@template.result(binding)
    finish
  end
end

并且app/views/index.html.erb的内容与问题本身中sse_time.html的内容相同。

现在点击http://localhost:3000开始在浏览器控制台上每5秒显示一次服务器时间。