Answer the question
In order to leave comments, you need to log in
A few questions about working with the EventSource library?
I use this thing https://github.com/Yaffle/EventSource
More or less figured out what's what. But still there are a few questions to understand.
Question number 1, what is the loop for?
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Access-Control-Allow-Origin: *");
$start = time();
$lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
if ($lastEventId == 0)
{
$lastEventId = (isset($_GET["key"])) ? (string)$_GET["key"] : 0;
}
$id = 0;
while(true)
{
if ((time() - $start) > 10)
{
break;
}
$updateProposals = array($id);
//echo ":" . str_repeat(" ", 2048) . "\n"; // 2 kB padding for IE
echo "retry: 2000\n";
echo "id: {$lastEventId}" . PHP_EOL;
echo "data: " . ProcessingData::load()->getJson($updateProposals) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
$id += 1;
sleep(4);
}
var es = new EventSource("/games/game/updateProposals/?id=<?=$game->game_id?>");
var open = function (event)
{
console.log('Открытие');
};
var listener = function (event)
{
console.log('OK');
$('.test').html(Math.random());
};
var error = function (event)
{
//if (event.readyState == EventSource.CLOSED)
if (EventSource.CLOSED == 2)
{
console.log('Соединение закрыто');
}
else
{
console.log('Другая ошибка');
}
};
es.addEventListener("open", open);
es.addEventListener("message", listener);
es.addEventListener("error", error);
if ((time() - $start) > 10)
{
break;
}
Answer the question
In order to leave comments, you need to log in
0. The library you mention every time is polyfill. It is needed to implement SSE in old and crooked browsers. It makes no sense to write about it every time (especially since you are trying to make a server).
1. This is a demo from the library. Just to see if the library works.
I don't even know what to answer to that. A cycle is needed to perform actions cyclically. Your CO.
What happens in the loop:
- if more than 10 seconds have passed, exit the work
- write data
- flush the buffer
- sleep for 4 seconds
What were you waiting for? The script did its job and died.
Even if you leave
ob_flush();
flush();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question