Myoo Thu
Myoo Thu

Reputation: 29

How do I implement server sent event in codeigniter?

I want to make a real time application with CI. So I write some code in controller (CI)

Here's my code:

  $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();

But, I get this error:

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

Ideas?

Upvotes: 2

Views: 4388

Answers (3)

Saty
Saty

Reputation: 22532

You have to set the content type:

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

Please read the manual

Upvotes: 2

mmeulstee
mmeulstee

Reputation: 45

For Codeigniter 3, you have to change:

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();

see example

Upvotes: 1

Imran Qamer
Imran Qamer

Reputation: 2265

from codeigniter docs: https://ellislab.com/codeigniter/user-guide/libraries/output.html

$this->output->set_content_type();

Permits you to set the mime-type of your page so you can serve JSON data, JPEG's, XML, etc easily.

$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'));

Important: Make sure any non-mime string you pass to this method exists in config/mimes.php or it will have no effect.

Second Option

Go to your application/config/mimes.php add 'txt' => 'text/event-stream', to $mimes array.

EDIT change your code to:

    $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();

Upvotes: 0

Related Questions