Swoole HTTP Server Working Example

Below is a fully working Swoole HTTP Server which starts and listens on 127.0.0.1 and port 9501.

<?php
$server = new Swoole\HTTP\Server("127.0.0.1", 9501);

$server->set([
    'worker_num' => 4,      // The number of worker processes to start
    'task_worker_num' => 4  // The amount of task workers to start
    'backlog' => 128,       // TCP backlog connection number
]);

// Triggered when new worker processes starts
$server->on("WorkerStart", function($server, $workerId)
{
    echo "Worker Started: $workerId\n";
});

// Triggered when the HTTP Server starts, connections are accepted after this callback is executed
$server->on("Start", function($server, $workerId)
{
    echo "Swoole HTTP Server Started @ 127.0.0.1:8501\n";
});

// The main HTTP server request callback event, entry point for all incoming HTTP requests
$server->on('Request', function(Swoole/Server/Request $request, Swoole/Server/Response $response)
{
    $response->end('<h1>Hello World!</h1>');
});

// Triggered when the server is shutting down
$server->on("Shutdown", function($server, $workerId)
{
    echo "Server shutting down...\n";
});

// Triggered when worker processes are being stopped
$server->on("WorkerStop", function($server, $workerId)
{
    echo "Worker Stopped: $workerId\n";
});

$server->start();

You can then start the server by running php server.php.