Skip to content

lazervel/sse

PHP SSE

A PHP library for Server-Sent Events (SSE) implementation

Total Downloads Latest Version Contributors Repository Size

Composer Installation

Installation is super-easy via Composer

composer require modassir/sse

or add it by hand to your composer.json file.

Server

Create a file server.php auto response message.

use Modassir\SSE\Connection\ConnectionInterface;
use Modassir\SSE\SSEComponentInterface;
use Modassir\SSE\SSE;

require __DIR__.'/vendor/autoload.php';

class Chat implements SSEComponentInterface
{
  public function __construct()
  {
    //
  }

  public function onOpen(ConnectionInterface $conn)
  {
    //
  }

  public function onMessage(ConnectionInterface $conn, $message)
  {
    $conn->export();
  }

  public function onError(ConnectionInterface $conn, $e)
  {
    //
  }
}

(new SSE(new Chat()))->run();

Create a file sender.php to send message.

use Modassir\SSE\Sender\Sender;

require __DIR__.'/vendor/autoload.php';

$sender = new Sender();

$sender->onSend(function() {
  echo 'message sent successfully!';
});

$sender->send($_POST['data']);

Client

var EventSource = new EventSource('server.php');

EventSource.onopen = function()
{
  console.log('Connection establish successfully!');
}

EventSource.onmessage = function(e)
{
  console.log(e.data);
}

EventSource.onerror = function()
{
  EventSource.close();
}

Send message from client side

function send(url, message)
{
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.onload = function() {
    if (xhr.readyState === xhr.DONE && xhr.status === 200) {
      console.log(xhr.response); // Outputs: 'message sent successfully!'
    }
  };
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhr.send(message);
}

// USE
document.querySelector('your_button').addEventListener('click', function() {
  const data = {uid: 1000046353, message: 'Hello Worlds!'};
  send('sender.php', {data});
});

Resources

About

A PHP library for Server-Sent Events (SSE) implementation

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Languages