Event Stream handling

KenHorse

Member
I am trying to get server sent event streams working.

As a test, I placed the following in a php file:

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

function sendMsg($msg) {

 echo "data: $msg" . PHP_EOL;
 echo PHP_EOL;

 flush();
}

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

When I load the page into FireFox (95.0.2 (64-bit)), it asks me if I want to save or open the file. Obviously it isn't handling the event stream properly (or my code is wrong)
 
1. Create an HTML file (e.g., sse.html) and place the following code inside it:
<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Events Test</title>
</head>
<body>
<script>
var eventSource = new EventSource('sse.php');

eventSource.onmessage = function(event) {
console.log('Received message: ' + event.data);
// Handle the received event data here
};
</script>
</body>
</html>

  1. Move your PHP code to a separate file (e.g., sse.php) and make sure it contains the headers and sendMsg() function as you originally had:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function sendMsg($msg) {
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
flush();
}

sendMsg('server time: ' . date("h:i:s"));
?>

  1. Open the sse.html file in Firefox. It will establish a connection with the sse.php file through the EventSource object in JavaScript, and the on message event handler will be triggered whenever a message is received from the server.
 
Hello this is Gulshan Negi
Well, you need to add these two line before your code at the top of your PHP file.

error_reporting(E_ALL);
ini_set('display_errors', 1);

It may be helpful for you.

Thanks
 
Back
Top