Swoole 並非傳統 MVC 框架,而是一個用純 C 語言編寫的 PHP 擴展,提供了**異步多線程 Server、異步 TCP/UDP Client、異步 MySQL/Redis、連接池、Task、毫秒定時器、異步文件讀寫、異步 DNS** 等能力。內置 Http/WebSocket/Http2 Server/Client。適用於即時通訊、游戲、物聯網、微服務等高併發場景。
Swoole:重新定義 PHP —— PHP 的異步、並行、高性能網絡通信引擎。
安裝擴展:pecl install swoole(參考 官方 Wiki)。
<?php
class Server {
private $serv;
public function __construct() {
$this->serv = new swoole_server("0.0.0.0", 9501);
$this->serv->set([
'worker_num' => 8,
'daemonize' => false,
'max_request' => 10000,
'dispatch_mode' => 2,
'debug_mode' => 1
]);
$this->serv->on('Start', [$this, 'onStart']);
$this->serv->on('Connect', [$this, 'onConnect']);
$this->serv->on('Receive', [$this, 'onReceive']);
$this->serv->on('Close', [$this, 'onClose']);
$this->serv->start();
}
public function onStart($serv) { echo "Start\n"; }
public function onConnect($serv, $fd, $from_id) {
$serv->send($fd, "Hello {$fd}!");
}
public function onReceive(swoole_server $serv, $fd, $from_id, $data) {
echo "Get Message From Client {$fd}:{$data}\n";
$serv->send($fd, "Server: {$data}");
}
public function onClose($serv, $fd, $from_id) {
echo "Client {$fd} close connection\n";
}
}
$server = new Server();
<?php
class Client {
private $client;
public function __construct() {
$this->client = new swoole_client(SWOOLE_SOCK_TCP);
}
public function connect() {
if (!$this->client->connect("127.0.0.1", 9501, 1)) {
echo "Error: {$this->client->errMsg}[{$this->client->errCode}]\n";
return;
}
$message = $this->client->recv();
echo "Get Message From Server: {$message}\n";
fwrite(STDOUT, "請輸入消息:");
$msg = trim(fgets(STDIN));
$this->client->send($msg);
}
}
$client = new Client();
$client->connect();
# 終端 1
php server.php
# 終端 2
php client.php
# 輸入文字回車,觀察雙向通訊
| 模塊 | 核心功能 |
|---|---|
| Swoole\Server | TCP/UDP/HTTP/WebSocket Server,多進程、事件驅動、Task 投遞 |
| Swoole\Client | 同步/異步 TCP/UDP/HTTP/WebSocket Client |
| Swoole\Coroutine | 協程調度器,提供 go、chan、defer、select 等 CSP 模型 |
| Swoole\Async | 異步文件讀寫、DNS 查詢、MySQL/Redis/PostgreSQL/HTTP Client |
| Swoole\Process | 進程管理、進程間通訊 (IPC)、信號處理 |
| Swoole\Timer | 毫秒級定時器、定時任務 |
| Swoole\Lock | 互斥鎖、讀寫鎖、信號量 |
| Swoole\Atomic | 原子計數器 |