Mastering High‑Performance PHP with Swoole: Multi‑Process, Coroutine, and Async I/O Guide
Learn how Swoole transforms PHP into a high‑performance, asynchronous server by detailing its multi‑process architecture, reactor‑worker‑task model, coroutine‑enabled I/O, and practical code examples for TCP clients, HTTP servers, and file operations, enabling scalable, non‑blocking applications.
Overview
Swoole is a high‑performance PHP extension that provides an efficient asynchronous, non‑blocking network I/O server built on epoll/kqueue and supports multi‑process and multi‑thread models. It lets developers focus on business logic while abstracting low‑level I/O details.
Concurrency Architecture
The extension uses a mixed mode: fully asynchronous execution combined with coroutine‑based "pseudo‑synchronous" programming, lowering the barrier to concurrent development without sacrificing performance.
Multi‑Process Model Example (server.php)
<?php
/**
* @desc Multi‑process model (Master‑Worker)
*/
declare(strict_types=1);
$server = new Swoole\Server('0.0.0.0', 9501);
// Configure processes
$server->set([
'worker_num' => 4, // 4 Worker processes
'reactor_num' => 2, // 2 Reactor threads
'task_worker_num'=> 2, // 2 Task workers
]);
// Connection event
$server->on('Connect', function ($server, $fd) {
echo "[0] Client: Connect.
";
});
// Data receive (Worker)
$server->on('receive', function ($server, $fd, $reactor_id, $data) {
$task_id = $server->task($data);
echo "[1] Dispatch AsyncTask: id={$task_id}
";
return $server->send($fd, "Server: {$data}");
});
// Async task processing (Task Worker)
$server->on('task', function ($serv, $task_id, $reactor_id, $data) {
sleep(3); // simulate heavy work
echo "[2] New AsyncTask[id={$task_id}]" . PHP_EOL;
$serv->finish("{$data} -> OK");
});
// Task result handling (Worker)
$server->on('Finish', function ($serv, $task_id, $data) {
echo "[3] AsyncTask[{$task_id}] Finish: {$data}" . PHP_EOL;
});
$server->start();Run the script with swoole-cli.exe server.php. After startup, use netstat to verify that port 9501 is listening, then connect via telnet or netcat.
Key Points of the Process Model
Reactor : A dedicated thread that monitors socket events (connect, read, write) using epoll, enabling efficient polling of thousands of connections without blocking other processes.
Worker : The main process pool that runs independent Reactor loops, receives events from the Reactor, and executes business logic such as HTTP parsing or database calls.
Task Worker : A separate pool for blocking or time‑consuming tasks (e.g., email sending, heavy calculations) to keep the I/O path non‑blocking.
Asynchronous I/O
Swoole’s async I/O combines non‑blocking system calls with an event‑driven loop, leveraging OS‑level multiplexing (epoll) to achieve "ready‑then‑process" behavior.
Async File Read
// Enable coroutine hook
Swoole\Runtime::enableCoroutine();
// Non‑blocking file read
$content = file_get_contents("large_file.txt");
var_dump($content);Coroutine‑Based HTTP Request
go(function () {
$http = new Swoole\Coroutine\Http\Client('tinywan.com', 80);
$http->get('/api/webman');
echo $http->body;
});Network I/O
Asynchronous TCP Client
use Swoole\Coroutine\Client;
go(function () {
$client = new Client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, 0.5)) {
echo "connect failed. Error: {$client->errCode}
";
}
// Send 100 concurrent requests
for ($i = 1; $i <= 100; $i++) {
$client->send("hello world
");
Co::sleep(0.1); // simulate interval
}
echo $client->recv();
$client->close();
});High‑Concurrency HTTP Server
declare(strict_types=1);
$http = new Swoole\Http\Server('0.0.0.0', 9501);
$http->on('Request', function ($request, $response) {
// Async MySQL query
$mysql = new mysqli('127.0.0.1', 'root', '123456', 'nacos', 3308);
var_dump($mysql);
// Concurrent queries
$results = [
'user' => $mysql->query('SELECT * FROM users LIMIT 10')->fetch_assoc(),
'product' => $mysql->query('SELECT * FROM tenant_info LIMIT 5')->fetch_assoc(),
];
$response->header('Content-Type', 'text/html; charset=utf-8');
$response->end(json_encode($results));
});
$http->start();This collection of examples demonstrates how Swoole enables PHP developers to build scalable, high‑throughput services by leveraging multi‑process, coroutine, and asynchronous I/O techniques.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
