Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/commandstring/reactphp-sse

Server Side Events with React/Http
https://github.com/commandstring/reactphp-sse

Last synced: 1 day ago
JSON representation

Server Side Events with React/Http

Awesome Lists containing this project

README

        

# commandstring/sse

Server-sent events with ReactPHP

# Channel
This is where all clients are stored, you can perform actions on all clients from here or specific clients.

# Client
This represents an active connection

# Example

```php
# index.php
getRequestTarget() === "/sse") {
$stream = new ThroughStream();
$client = new Client($stream, $clientCount++);

echo $clientCount . PHP_EOL;

$channel->addClient($client);

return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
'Content-Type' => 'text/event-stream'
),
$stream
);
}

return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
'Content-Type' => 'text/html'
),
file_get_contents("index.html")
);
}))->listen(new React\Socket\SocketServer('127.0.0.1:8000'));

Loop::addPeriodicTimer(1, function () use ($channel) {
$channel->sendMessageToAll(mt_rand(0, 9999), "item");
});
```

```html




SSE




List




let eventStream = new EventSource("http://localhost:8000/sse");

eventStream.addEventListener("item", (event) => {
$("#items").append(`<li>${event.data}</li>`);
console.log(event);
});

eventStream.addEventListener("open", () => {
console.log("connected");
$.toast({
"title": "Connected to SSE server"
});
})

```