Using server sent events together with websockets in webots streaming-viewer

  javascript, php, server-sent-events, webots, websocket

I’m using webots streaming-viewer to stream an online simulation. I give points to each simulation. The javascript code to get the streaming data is already provided in the resources of the webots and it uses websockets to get the data. While this simulation is happening I’m writing the points to a text file and if the file is modified I send the contents of the file to the client using server send events. But this point’s data is not received at the client-side. When I use this code without the websocket code it works. But when integrating it with the websocket code it doesn’t work. Here are my javascript and php code. Thank you.

Javascript

if (typeof EventSource !== 'undefined') {
    var evtSource = new EventSource('sse_demo.php');
    evtSource.onmessage = function (event) {
        console.log(event.data);
    };
} else {
    console.log("error");
}

Php

<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
$lastMod = 0;
$filename = "tmp.txt";
$filetext = '';
$last = '';
while (true) {
    clearstatcache();
    $time = filemtime("./tmp.txt");
    if($time != $lastMod){
        $lastMod = $time;
        $file = fopen($filename, "r");
        if ($file == false) {
            echo ("Error in opening file");
            exit();
        }
        $filesize = filesize($filename);
        $filetext = fread($file, $filesize);
        fclose($file);
        echo 'data: ' .$filetext . "nn";
    }
    ob_end_flush();
    flush();
    if (connection_aborted()) break;
    sleep(2);
}

Source: Ask PHP

LEAVE A COMMENT