2015-05-29 90 views
2

我想用CI创建实时应用程序。 所以我写控制器(CI)的一些代码如何在codeigniter中实现服务器发送的事件?

这里是我的代码:

$this->output->set_content_type('text/event-stream'); 
    $this->output->set_header('Cache-Control: no-cache'); 
    $time = date('r'); 
    $output="data: The server time is: {$time}\n\n"; 
    flush(); 

但是,我得到这个错误:

EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.

想法?

+0

更改MIME类型 –

回答

0

从笨文档: https://ellislab.com/codeigniter/user-guide/libraries/output.html

$这 - >输出 - > set_content_type();

允许您设置的MIME类型的网页,让您可以轻松地服务于JSON数据,JPEG的,XML等。

$this->output->set_content_type('application/json')->set_output(json_encode(array('foo' => 'bar'))); 

$this->output->set_content_type('jpeg') // You could also use ".jpeg" which will have the full stop removed before looking in config/mimes.php 
    ->set_output(file_get_contents('files/something.jpg')); 

要点:确保你传递给该方法的任何非MIME字符串中的config/mimes.php存在,或者它不会有任何效果。

第二个选项

转到您的application/config/mimes.php 添加'txt' => 'text/event-stream',$mimes阵列。

编辑 改变你的代码:

$time = date('r'); 
    $output="data: The server time is: {$time}\n\n"; 
    $this->output->set_content_type('text/event-stream')->set_output($output); 
    $this->output->set_header('Cache-Control: no-cache'); 
    flush(); 
+0

我也更改了mimes.php。但我无法解决这个错误。感谢Imram Qamer。 –

+0

是的,你改变了mime tipes,但你没有添加输出函数调用set_output($输出),检查我的修改答案 –

2

你必须设置内容类型:

$this->output->set_content_type('text/plain', 'UTF-8'); 
$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate') 

请阅读manual

1

对于笨3,您需要更改:

set_output => _display 

$time = date('r'); 
$output="data: The server time is: {$time}\n\n"; 
$this->output->set_content_type('text/event-stream')->_display($output); 
$this->output->set_header('Cache-Control: no-cache'); 
flush(); 

查看示例

相关问题