What Is the PHPTS "Event-Triggered Task"?
In one sentence: it gives PHP "long connection + event-driven" capability on Windows — five types of event sources (WebSocket, TCP, MQTT, serial port, and timer) are all held uniformly by a single Rust gateway, and each incoming event delegates a one-time script execution to PHP, with the response returned along the original path. PHP developers don't need to write long-running processes or touch sockets; they simply write ordinary scripts that "receive input, process it, and echo output" as usual. Whether PHP runs in an HTTP request, on the command line, or in an event task, it can proactively push messages to clients.
1. What problem does it solve
PHP's traditional execution model is 'one execution per HTTP request': a request comes in, the script runs to completion, and the process is returned; it is naturally unsuitable for holding long-lived connections. But IoT and real-time workloads precisely need long-lived connections—barcode scanners continuously emit data from serial ports, 4G data transmission modules transparently transmit BeiDou positioning over TCP, browsers need real-time WebSocket push, and device messages arrive continuously via MQTT.
Traditional solutions either switch languages (Node.js, Go) or adopt resident-memory frameworks such as Swoole/Workerman—the former overturns the tech stack, while the latter changes PHP's programming mindset (memory leaks, state pollution, and hot updates are all new problems).
PHPTS's answer to 'event-triggered tasks' is to separate 'connections' from 'logic':
2. Five types of event sources
WebSocket server
Typical scenarios are real-time browser push and H5 large screens. Routes to different scripts by handshake path; dual listening on ws:// (default 3380) and wss:// (default 3343); protocol-layer Ping/Pong heartbeat; ?client_id= specifies client identity, and a new connection with the same ID replaces the old one.
TCP server
For 4G/BeiDou data transmission pass-through, DTUs, and custom-protocol devices. One rule per independent listening port (default starting at 59301); three framing modes: idle idle framing (default 50ms), line delimiter-based framing, none raw byte segments; Nagle is disabled on connection.
MQTT subscription
Acts as a processing node on the IoT message bus. By default connects to built-in NanoMQ or an external MQTT server; topic wildcard matching (+/#); received messages are handed to PHP for processing, and reply topics also support wildcard expansion; QoS1 automatically sends PUBACK, and reconnects with 5-second backoff after disconnection.
Serial port listening
Used for RS485-to-MQTT data transmission, barcode scanners, weighing meters, etc. One rule per COM port, with independent line parameters and scripts; framing follows the same conventions as TCP, and in idle mode timing is based on 'the moment the last byte arrives'; 50ms of silence forms a frame.
Timer
Periodic collection, daily reports, and wall-clock tasks. interval anti-drift grid + daily/weekly/monthly local wall-clock triggering; reentrancy switch: when the previous round has not returned, the current round can be skipped, or multiple parallel copies of the same script can be allowed.
The five subservices start and stop independently and are not tied to one another—an exception in a single subservice is only marked as error and will not bring down the entire gateway.
In addition, there is a shared HTTP push interface (default 127.0.0.1:3379): any ordinary PHP script (Nginx Web, CLI, scheduled script) can, with a single HTTP POST, actively push data to online WebSocket clients, TCP connections, or serial ports, supporting multiple targets such as by client ID, by phpts_kv shared-memory key, and by port broadcast. Server → Client active push no longer depends on the event script itself.

3. Engine: IOCP Completion Port
The gateway's three network subservices—WebSocket, TCP, and MQTT—are all built on Windows IOCP (I/O Completion Port, I/O completion port)—the asynchronous I/O mechanism natively provided by the Windows kernel, and also the common foundation for high-performance server software such as SQL Server and IIS on Windows.
Its working mode is 'post first, complete later':
- The application 'posts' a buffer together with a read request to the kernel (overlapped operation), then returns immediately; the thread does not wait for data;
- After the NIC receives data, the kernel copies the data directly into the buffer you posted, then posts a 'completion notification' to the completion port with the actual byte count;
- A small number of I/O threads take completion notifications from the completion port and process the data already lying in the buffer.
With this, the PHPTS gateway achieves: only 2 fixed I/O worker threads, yet it can simultaneously serve the heartbeats, send/receive, and routing of tens of thousands of connections. All potentially time-consuming blocking operations (PHP delegation, shared-memory scanning) are dispatched to an independent blocking thread pool and never occupy these 2 I/O threads—no matter how slow a script is, it cannot block other connections' heartbeats and send/receive.
4. Advantages of IOCP over Linux epoll
epoll is the de facto standard for high-concurrency network programming on Linux, but it and IOCP belong to two generations of models: epoll is Reactor (readiness notification), and IOCP is Proactor (completion notification). The differences are reflected in four aspects.

1. 'Readable' vs 'already read'
epoll only tells you 'this fd is readable'; the data still remains in the kernel buffer. The application must call recv again to copy the data out, and must also handle details such as partial reads, EAGAIN retries, and draining reads in edge-triggered mode. A complete packet receive takes at least two rounds of system calls (epoll_wait + recv), and the read action occurs after the notification.
IOCP reverses the order: the kernel first copies data into the application buffer; when the notification arrives, the data is already in place, and what the application gets is 'read complete + byte count + data'. There is no EAGAIN loop, no race where 'it is ready but cannot be read', fewer system calls, and simpler event-loop code—it processes results, not possibilities.
2. Who owns buffer responsibility
Under the epoll model, when to allocate a buffer, how large to allocate, and what to do if only half is read are all mental burdens for the application; as connections increase, per-connection read-buffer management itself becomes a source of complexity. Under the IOCP model, the application only posts buffers; copying is completed by the kernel before notification, and 'when to read and how much to read' is fulfilled by the kernel according to the actual amount that arrives. Application-side framing logic (such as PHPTS's idle silent framing) can be built on definite byte-arrival events.
3. Kernel-provided thread scheduling
This is IOCP's most underestimated advantage: the completion port itself is a kernel-level thread pool.
- When creating a completion port, you can specify the 'maximum number of concurrently active threads'; the kernel guarantees that no more than that number of threads run at the same time, and excess threads are automatically suspended;
- Waiting threads are woken in LIFO (last in, first out) order—the thread that went to sleep last is woken first, and its stack and cache are the hottest, minimizing context-switch overhead;
- When multiple threads wait on the same port, the kernel delivers precisely, and there is naturally no thundering-herd problem.
With epoll, all of this must be built by yourself: thread pools, load balancing, EPOLLEXCLUSIVE/SO_REUSEPORT to mitigate the thundering herd... which amounts to recreating in the application layer what already exists in the IOCP kernel. The concise structure of the PHPTS gateway—'2 I/O threads + blocking thread pool'—directly benefits from this kernel scheduling.
4. Unified I/O abstraction
epoll only covers 'pollable fds' (sockets, pipes, etc.), and ordinary disk files are not applicable (always ready, equivalent to no async). IOCP uniformly covers sockets, files, and named pipes—the same completion-notification semantics. PHPTS's control channel (named pipe), logging and configuration I/O, and network events share the same mental model, giving better engineering consistency.
Objectively speaking
Linux's io_uring is catching up on the 'completion notification' lesson, and its direction converges with IOCP—which precisely confirms the advanced nature of the Proactor model. On Windows, IOCP is not new; it is a native kernel capability polished for more than twenty years. PHPTS choosing the Rust async runtime (under Windows its underlying layer is IOCP) rather than porting epoll-style polling means standing directly on the foundation of Windows' performance ceiling.
V. Asynchronous Gateway + Synchronous PHP: Engineering Design at the Boundary
This architecture appears asynchronous and non-blocking to the outside, but the PHP script itself still executes synchronously. Three boundary designs determine whether it is usable:
- Serial delegation per connection: On the same WS/TCP connection, only one request is in flight at any given time; the next message is not read until a response or timeout—sacrificing per-connection throughput in exchange for strictly ordered responses. Across connections, execution is fully parallel; concurrency capacity is determined by the number of task pool processes.
-
Timeout does not kill the connection: The global default is 300 seconds, which can be overridden per rule; the timeout value is also delivered to the PHP side
set_time_limit()for coordination. After a timeout, the gateway only silently discards the response for this request; the connection remains open, and subsequent messages are delegated as usual—slow scripts do not punish the client. -
Output is protocol data: Whatever the script
echo, the client receives exactly that (WS text frame / TCP raw bytes / MQTT response topic / serial bytes). When the script output is exactly__PHPTS_CLOSE__, the gateway actively closes the connection—a single string at the business layer can control the connection lifecycle.
Cross-event state is stored in the phpts_kv shared memory extension (a cross-process key-value store; when a client disconnects, the gateway automatically cleans up its registration) or Redis, and PHP remains stateless.
VI. How Simple Is It to Write a PHP Event Script
<?phpini_set('display_errors', '0'); // 输出就是协议数据,警告不能混进去error_reporting(E_ALL);$raw = file_get_contents('php://input'); // 消息原始字节$clientid = $_SERVER['PHPTS_EVENT_CLIENTID'] ?? ''; // 网关注入的客户端连接 ID$clientip = $_SERVER['PHPTS_EVENT_CLIENTIP'] ?? ''; // 网关注入的客户端 IP 地址//把客户端连接 ID 存进进程间共享内存(phpts_kv 扩展),假设 $raw 中包含用户 ID 1001,保存用户 ID 与 客户端 ID 的对应关系phpts_kv_set('user:1001', $_SERVER['PHPTS_EVENT_CLIENTID'], 86400); //超过 1 天自动删除,也可以不设置,保持永久登记直到客户端断开连接$data = json_decode($raw, true);echo json_encode(['ok' => true,'client' => $clientid,'recv' => $data,'time' => date('c'),], JSON_UNESCAPED_UNICODE); // echo 输出内容,即可发送回客户端
No resident process, no event loop, no callback hell. If you can write an API in PHP, you can write event tasks.
VII. How Simple Is It to Write a (Server → Client) Active Push Script
<?php// PHP 无论运行在 HTTP 请求、命令行还是事件任务中,都可凭刚才保存的客户端 ID,向客户端主动发消息$client = phpts_kv_get('user:1001'); // 从共享内存获取客户端 IDif (!$client) { exit('client offline'); } // 客户端离线,系统会自动从共享内存删除对应键值对
// 向 WebSocket 客户端发送消息为例,换成 /tcp/send 则为 TCP$url = 'http://127.0.0.1:3379/ws/send?client=' . urlencode($client) . '&token=<token>'; // 把 Token 换成「权限 Token」框里的值(留空则删掉该参数)
// 多目标推送:client= 与 key= 均支持逗号分隔多个值,两者可同时给出取并集;key= 由网关按 phpts_kv 键自动查找该键登记的客户端 ID 再推送$url = 'http://127.0.0.1:3379/ws/send?key=' . rawurlencode('user:1001,user:1002') . '&token=<token>';
$ctx = stream_context_create(['http' => [ 'method' => 'POST', 'header' => "Content-Type: text/plain\r\n", 'content' => json_encode(['type' => 'notify', 'msg' => 'hello']), 'timeout' => 3,]]);echo file_get_contents($url, false, $ctx); // {"ok":true}
Whether PHP runs in an HTTP request, on the command line, or in an event task, it can actively push messages to clients. There is also an “Active Push Debugging Assistant” visualization tool to help you debug the issue of sending messages from the “server side” to the “client side”.

The WebSocket client debugging assistant simulates a WS client and receives “Hello World!” sent from the “server side”.

VIII. Typical Scenarios
-
IoT data transmission: RS485 devices connect via serial port rules; after parsing, the script writes to the database or forwards via MQTT. A 4G BeiDou positioning module reports through a TCP transparent transmission port;
idleperforms framing to restore write boundaries, and the script binds device identity by IMEI. - Web real-time business: The browser connects to the gateway via WebSocket; after ordinary PHP business code in Nginx finishes processing an order, it sends an HTTP POST to the push interface, and the result appears on the page in real time.
- Message bus integration: Subscribe to MQTT topics; the script performs protocol translation, writes to the database, and then sends back via a response topic—PHP becomes a processing node in the IoT message pipeline.
- Periodic tasks: A timer triggers the daily report script by wall clock; reentrancy protection ensures that if the previous round has not finished, another will not stack on top.
IX. Conclusion
The essence of “event-triggered tasks” is to use the most mature asynchronous I/O mechanism in the Windows kernel (IOCP) to handle connections and concurrency, and to put PHP back in the position where it is most comfortable. It does not require you to change languages or change your programming model, yet it enables PHP, for the first time on Windows, to access the world of long connections and IoT with native-level performance.
Connections belong to the gateway, logic belongs to PHP—this is PHPTS’s answer to “Can PHP do real-time services?”
Comments 0 comments
No comments yet. Be the first to comment.