1. Go to this page and download the library: Download phpdot/server-swoole 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/ */
phpdot / server-swoole example snippets
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPdot\Server\Swoole\SwooleServer;
use PHPdot\Server\Swoole\Config\ServerConfig;
$factory = new Psr17Factory();
$config = new ServerConfig(workerNum: 4);
$server = new SwooleServer($factory, $config);
$server->serve($handler, '0.0.0.0', 8080);
$server->push($fd, $data); // send data to a client
$server->wsDisconnect($fd); // disconnect a client
$server->isEstablished($fd); // check if connection is active
$server = new SwooleServer($factory, new ServerConfig(taskWorkerNum: 4));
$server->onTask(function (Server $server, Task $task): void {
// runs in a task worker process
$result = processHeavyWork($task->data);
$task->finish($result);
});
$server->onFinish(function (Server $server, int $taskId, mixed $data): void {
// result returned to the requesting worker
});
// dispatch from anywhere after serve()
$server->task($data); // async dispatch
$server->taskCo([$data1, $data2], timeout: 1); // coroutine dispatch, wait for results
$server->finish($result); // return result from task worker
$timerId = $server->tick(5000, function (): void {
// runs every 5 seconds
});
$server->after(10000, function (): void {
// runs once after 10 seconds
});
$server->clearTimer($timerId);
$server->exists($fd); // check if connection exists
$server->close($fd); // close a connection
$server->getClientInfo($fd); // get connection details
$server->getClientList(); // list connected file descriptors
$server->sendMessage($data, $workerId); // send message to another worker
use PHPdot\Server\Swoole\CallbackStreamInterface;
final class SseStream implements StreamInterface, CallbackStreamInterface
{
public function __construct(private readonly Closure $producer) {}
public function getCallback(): Closure
{
return function (Closure $write): void {
($this->producer)($write);
};
}
}