Swoole HTTP Server Working Example

4.x is outdated, please check the latest version 22.x

Latest version: pecl install openswoole-22.1.2

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

$server = new Swoole\HTTP\Server("", 9501);

    '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 @\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";


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

Last updated on August 31, 2022