1. Go to this page and download the library: Download phasync/swerve library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// swerve.php
use phasync;
use phasync\IOException;
return new Swerve\RequestHandler(function (Swerve\ClientRequest $request) {
$request->sendResponseHeaders(200, ['content-type' => 'text/event-stream', 'cache-control' => 'no-cache']);
$request->flush(); // the head goes out now, not with the first event
try {
for ($n = 1; ; ++$n) {
$request->write("data: $n\n\n");
phasync::sleep(1);
}
} catch (IOException) {
// the client left
}
});
use Swerve\Swerve;
Swerve::ini(['memory_limit' => '512M']); // php.ini settings, applied by swerve's startup restart
Swerve::onWorkerStart(function () { // in every worker, before the application loads
// set up what the worker shares between requests; coroutines started here run for its life
});
$locales = new WeakMap(); // per Scope
phasync::onScopeChange(function (Scope $new, ?Scope $old) use ($locales) {
if (null !== $old) {
$locales[$old] = setlocale(LC_ALL, 0);
}
setlocale(LC_ALL, $locales[$new] ?? 'C');
});
use Swerve\Swerve;
Swerve::publish('chat', $message);
foreach (Swerve::subscribe('chat') as $message) {
// every message published to 'chat' from the moment subscribe() returned
}