如何在codeigniter中实现服务器发送事件?
我想用CI制作一个实时应用程序。 所以我在控制器(CI)中编写了一些代码 这是我的密码:如何在codeigniter中实现服务器发送事件?,codeigniter,server-sent-events,Codeigniter,Server Sent Events,我想用CI制作一个实时应用程序。 所以我在控制器(CI)中编写了一些代码 这是我的密码: $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()
$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的响应的MIME类型(“text/html”)不是
“文本/事件流”。正在中止连接
想法?来自codeigniter文档:
$this->output->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中,否则它将无效
第二选项
转到您的应用程序/config/mimes.php
添加'txt'=>“文本/事件流”,
到$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();
您必须设置内容类型:
$this->output->set_content_type('text/plain', 'UTF-8');
$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate')
请阅读Codeigniter 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();
参见示例我在mimes.php中也做了更改。但我不能解决这个错误。谢谢Imram Qamer。是的,您更改了mime提示,但您没有将输出函数调用添加为set_output($output),请检查我的修改答案