swoole-src README

项目的 README,来自 github.com/swoole/swoole-src。合并为一个 markdown 文件:README.md。

Swoole logo

An event-driven networking engine and coroutine runtime for PHP

CI Codecov Latest release License

Swoole is a PHP extension for building persistent network services and concurrent I/O applications. Its C/C++ core provides an event loop, coroutine scheduler, servers, clients, and protocol implementations. The bundled PHP library adds connection pools, proxies, and higher-level utilities. Use Swoole for HTTP APIs, WebSocket applications, TCP/UDP gateways, and services that need to handle many connections without a separate PHP process for every request.

Version note: master is the development branch for Swoole 6.3 and currently supports PHP 8.2–8.5. For production, choose a released version and check the supported versions for its PHP compatibility and maintenance status.

At a glance

Capability Main APIs Typical use
Event-driven servers Swoole\Server, Swoole\Event TCP, UDP, Unix sockets, connection events
Coroutines Swoole\Coroutine, Channel, Socket Concurrent I/O and task coordination
HTTP and WebSocket Swoole\Http\Server, Swoole\WebSocket\Server APIs, streaming responses, real-time messaging
Coroutine clients Swoole\Coroutine\Client, Swoole\Coroutine\Http\Client Calls to TCP and HTTP upstream services
Runtime hooks Swoole\Runtime Coroutine-aware behavior for supported PHP functions
Processes and shared data Swoole\Process, Swoole\Table, atomics Background work and interprocess state
Timers and system I/O Swoole\Timer, Swoole\Coroutine\System Scheduled work, file and process operations

How Swoole works

The Reactor watches sockets and other registered file descriptors, then dispatches events to callbacks. Servers can run multiple worker processes to use multiple CPU cores. Within a worker, coroutines let other tasks run while one task waits for supported I/O. Task workers provide a separate execution path for jobs that should not hold up request handling.

Coroutines are a concurrency tool, not automatic CPU parallelism. A CPU-intensive PHP loop still occupies its worker until it yields or finishes. Use worker or task processes, or optional thread support, when work needs parallel execution.

Swoole workers are long-lived. Global variables, static state, and open resources can survive beyond one request. Close or recycle connections, enforce timeouts, and keep per-request data out of process-wide state. Ordinary PHP variables are not shared between worker processes; use IPC, Table, or external storage when data must be shared.

Functional modules

Servers and network protocols

Swoole\Server handles TCP, UDP, and Unix socket services. It supports multiple listening ports, worker and task worker processes, connection management, heartbeats, and configurable packet boundaries such as length fields or EOF markers. Swoole\Event lets an application register its own file descriptors with the event loop, while Swoole\Timer schedules one-off or recurring callbacks.

Choose the server API that matches the protocol and lifecycle:

Requirement Starting point
Custom TCP/UDP protocol, multiple ports, or task workers Swoole\Server
HTTP API with request callbacks and worker processes Swoole\Http\Server
HTTP service controlled from a coroutine Swoole\Coroutine\Http\Server
WebSocket handshake and bidirectional frames Swoole\WebSocket\Server

See the TCP server and multiple-port server examples. Server callbacks can use task() to dispatch work to task workers and sendMessage() for messages between workers.

Coroutines and coordination

Swoole\Coroutine\run() starts a coroutine environment, and go() starts a coroutine. Swoole\Coroutine\Socket and Swoole\Coroutine\System expose I/O operations that cooperate with the scheduler. Channel passes values between coroutines; the PHP library also provides WaitGroup and Barrier for waiting on groups of tasks. Set timeouts for upstream calls and handle cancellation or failures explicitly.

Swoole\Runtime::enableCoroutine() hooks selected blocking PHP functions so they can yield inside a coroutine. Depending on the hook flags, build options, and loaded PHP extensions, this can cover streams, files, sleep functions, cURL, and supported database operations. Hooks do not transform arbitrary third-party C library calls. Use the explicit coroutine client or Socket APIs when precise I/O behavior matters.

HTTP, HTTP/2, and WebSocket

Swoole\Http\Server serves HTTP through request callbacks; Swoole\Coroutine\Http\Server offers a coroutine-managed server. Request and response APIs cover headers, cookies, uploads, status codes, file delivery, and streamed output. The HTTP/2 implementation supports multiplexed streams, while WebSocket provides upgrade handling and frame encoding and decoding. Compression and TLS depend on the relevant build options and environment.

Coroutine HTTP and HTTP/2 clients call upstream services without occupying a worker while waiting for I/O. For examples and edge cases, see the HTTP/2 examples and WebSocket tests. Applications still need to define their own message formats, authentication, and reconnect behavior.

Clients, DNS, and asynchronous system operations

Coroutine TCP/UDP clients, HTTP clients, and the lower-level Socket API offer different levels of control over connection setup, timeouts, and message framing. Swoole\Coroutine\System provides file and process operations. Optional c-ares integration supports DNS resolution; optional io_uring integration provides additional asynchronous I/O paths on Linux.

For database access, combine the appropriate PHP driver with supported runtime hooks, or use the PHP library's PDO, MySQLi, and Redis connection pools. A pool manages connection reuse; whether an operation yields depends on the driver and hook configuration.

Processes, threads, and the PHP library

Swoole\Process and Swoole\Process\Pool manage independent workers. Swoole\Table holds structured data shared between processes, and atomic values and messages support coordination. A table is useful for small, frequently accessed state; use a database for persistence or complex queries.

Thread APIs are optional and require a ZTS build of PHP. Use Swoole's thread-safe containers for data shared by threads rather than assuming ordinary PHP variables are safe to share. The bundled library/src/core/ directory also includes FastCGI, name resolvers, remote objects, connection pools, and other utilities. Available features can differ between Swoole branches.

Quick start

Install

Install a released version through PECL:

pecl install swoole

To build the checked-out source, install PHP development tools and a C/C++ compiler, then run:

phpize
./configure
make -j"$(nproc)"
sudo make install

Add extension=swoole.so to the php.ini used by the PHP CLI and verify with php --ri swoole. To load it for one command instead, use php -d extension=swoole.so --ri swoole. Run ./configure --help before enabling optional integrations.

Start an HTTP server

Save this example as server.php:

<?php

$server = new Swoole\Http\Server('127.0.0.1', 9501);
$server->set(['worker_num' => 2]);
$server->on('request', static function ($request, $response): void {
    $response->header('Content-Type', 'text/plain; charset=utf-8');
    $response->end("Hello, Swoole!\n");
});
$server->start();

Run php server.php in one terminal and curl http://127.0.0.1:9501/ in another. The server keeps running until you stop it with Ctrl+C.

Run concurrent tasks

Both tasks below wait for 0.1 seconds. While one is waiting, the scheduler can run the other:

<?php

use Swoole\Coroutine\Channel;
use Swoole\Coroutine\System;
use function Swoole\Coroutine\go;
use function Swoole\Coroutine\run;

run(function (): void {
    $results = new Channel(2);

    foreach ([1, 2] as $id) {
        go(function () use ($id, $results): void {
            System::sleep(0.1);
            $results->push("task $id done");
        });
    }

    echo $results->pop(), PHP_EOL;
    echo $results->pop(), PHP_EOL;
});

Optional build features

The default build provides the basic server and coroutine APIs. Enable integrations when the required system libraries or PHP extensions are available:

Configure option Purpose
--enable-sockets Integration with the PHP sockets extension
--with-openssl-dir=DIR TLS/SSL support
--enable-swoole-curl Coroutine cURL support
--enable-swoole-pgsql PostgreSQL support
--enable-cares c-ares DNS support
--enable-iouring, --enable-uring-socket Linux io_uring features
--enable-swoole-thread Thread support; requires ZTS PHP

Check ./configure --help and config.m4 for the options and dependencies in your branch. See the Windows notes for platform-specific details.

Documentation and development

After building the extension, run a focused PHP regression test with:

PHPT=1 php -n run-tests.php -n -d extension=modules/swoole.so \
  tests/swoole_http_server/create_request_large_upgrade.phpt

Report bugs and propose features through Issues. Submit code changes through pull requests with relevant tests. Report security issues privately to [email protected] rather than disclosing them in a public issue.

License

Swoole is licensed under the Apache License 2.0.

swoole-src (swoole/swoole-src)

正在搜索数据库…

这是做什么的?Swoole 是一个 PHP 的事件驱动、异步、基于协程的并发库,专为高性能而设计。
它是一个框架,还是装到 PHP 本身里面的东西?它是一个以 C++ 编写的原生 PHP 扩展形式发布的库:你把它安装到 PHP 运行环境里,然后在自己的 PHP 代码中调用它的 API。
在编译之前,我的机器需要满足什么条件?需要 Linux、macOS,或者通过 Cygwin 或 WSL 使用的 Windows;PHP 8.2.0 或更高版本(版本越高性能越好);编译还需要 GCC 4.8 或更高版本。
它在 Windows 上能原生运行吗?不能——在 Windows 上必须在 Cygwin 或 WSL 下编译;Linux 和 macOS 才是原生支持的平台。README 还建议使用最新版本,以获得最佳的稳定性和功能。
我实际能用它来做什么?适合阻塞式 I/O 会拖慢速度的 PHP 服务:长时间运行的事件驱动网络应用和服务器——WebSocket 就是它的核心使用场景之一——用协程来处理大量并发连接。
我不想往系统里的 PHP 装任何东西,能先试用一下吗?可以——Quick Start 会通过 Docker 运行一个 Swoole 程序,你可以在容器里先做实验,再决定要不要在本地编译这个扩展。
这个项目成熟吗?非常成熟——开发始于 2012 年,GitHub 上大约有 18.9k 颗星,CI 覆盖核心、扩展和框架的测试,还有专门的 io_uring 工作流。
WebSocket 是不是一等公民的使用场景?是的——websocket 与协程、事件驱动 I/O 一起被列在项目的核心主题里,所以用 PHP 编写 WebSocket 服务器是主流用法。
有哪些类似的项目?muduo, libevent, workflow, compio, vert.x, concurrentqueue, kividb, mummy
作者
swoole
大小
58.3 MB
星标
18.9K
时长
14年
提交 · 90 天