OpenSwoole HTTP Server Working Example

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

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

<?php
$server = new OpenSwoole\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 "OpenSwoole 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(OpenSwoole\Server\Request $request, OpenSwoole\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.

Last updated on September 20, 2022