PHP Classes

File: appphp/sse.php

Recommend this page to a friend!
  Classes of Rodrigo Faustino   Chat SSE   appphp/sse.php   Download  
File: appphp/sse.php
Role: Example script
Content type: text/plain
Description: Example script
Class: Chat SSE
Exchange chat messages using server-sent events
Author: By
Last change:
Date: 1 month ago
Size: 628 bytes
 

Contents

Class file image Download
<?php

require 'vendor/autoload.php';
use
Chat\App\Chat;

set_time_limit(0);

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

session_write_close();
$chat = new Chat();
$lastId = isset($_GET['lastId']) ? (int)$_GET['lastId'] : 0;

while (
true) {
    if (
connection_aborted()) {
        break;
    }
   
$messages = $chat->getMessages($lastId);
    if (
count($messages) > 0) {
       
$lastMessage = end($messages);
       
$lastId = $lastMessage['id'];

        echo
"id: {$lastId}\n";
        echo
"data: " . json_encode($messages) . "\n\n";
    }

   
ob_flush();
   
flush();
   
sleep(1);
}