PHPackages                             ant-framework/coroutine - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. ant-framework/coroutine

ActiveLibrary[Queues &amp; Workers](/categories/queues)

ant-framework/coroutine
=======================

v0.1.0(9y ago)230MITPHPPHP &gt;=5.5.0

Since Apr 24Pushed 9y ago1 watchersCompare

[ Source](https://github.com/ant-framework/coroutine)[ Packagist](https://packagist.org/packages/ant-framework/coroutine)[ RSS](/packages/ant-framework-coroutine/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

Co stack
========

[](#co-stack)

基于ReactPHP的携程堆栈模块,以同步的方式书写异步代码

### 使用ReactPHP异步回调模式

[](#使用reactphp异步回调模式)

```
include "vendor/autoload.php";

$loop = \React\EventLoop\Factory::create();
// 监听并绑定8000端口
$socket = stream_socket_server(
    "tcp://0.0.0.0:8000",
    $errorCode,
    $errorMessage,
    STREAM_SERVER_BIND | STREAM_SERVER_LISTEN
);

// 设置非阻塞
stream_set_blocking($socket, false);

// 等待新连接到来
$loop->addReadStream($socket, function ($stream, $loop) {
    $newStream = @stream_socket_accept($stream);
    stream_set_blocking($newStream, false);
    // 等待新连接可读
    $loop->addReadStream($newStream, function ($newStream, $loop) {
        echo fread($newStream, 8192);
        // 等待50ms后响应
        $loop->addTimer(0.05, function () use ($loop, $newStream) {
            // 等待新连接可写
            $loop->addWriteStream($newStream, function ($newStream, $loop) {
                fwrite($newStream, "HTTP/1.0 200 OK\r\nContent-Length: 11\r\n\r\nHello world");
                // 断开连接
                fclose($newStream);
                $loop->removeStream($newStream);
            });
        });
    });
});

$loop->run();
```

### 使用Coroutine

[](#使用coroutine)

- 在使用Coroutine的情况下,代码是以同步的方式书写的,但是运行模式是以异步的方式运行,在遇到IO时,程序会避开等待,去执行其他任务,等到IO完成后,切换回之前的上下文

```
include "vendor/autoload.php";

// 监听并绑定8000端口
$serverSocket = stream_socket_server(
    "tcp://0.0.0.0:8000",
    $errorCode,
    $errorMessage,
    STREAM_SERVER_BIND | STREAM_SERVER_LISTEN
);

// 设置非阻塞
stream_set_blocking($serverSocket, false);

Ant\Coroutine\GlobalLoop::addReadStream($serverSocket, function ($stream) {
    Ant\Coroutine\Task::start(function () use ($stream) {
        $newStream = @stream_socket_accept($stream);
        stream_set_blocking($newStream, false);

        try {
            // 切换上下文,等到流读完时切换回当前上下文
            echo (yield \Ant\Coroutine\asyncRead($newStream, 8192));

            // 沉睡50ms后
            yield Ant\Coroutine\sleep(0.05);

            // 切换上下文,写入完成后,切换回当前上下文
            yield \Ant\Coroutine\asyncWrite($newStream, "HTTP/1.0 200 OK\r\nContent-Length: 11\r\n\r\nHello world");
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        } finally {
            // 断开连接
            fclose($newStream);
        }
    });
});
```

### Todo

[](#todo)

- Fork当前任务
- 协程上下文,参考Koa中间件功能
- 异步客户端 (redis, mysql, http)
- defer,当协程完成时,触发defer(资源回收机制)
- 保存任务上下文,每当触发事件时,clone一个进行触发

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3308d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/755ad6fc19e3debf94bfe59b23b134b06d92c16a989411f0f38553b18c7a107f?d=identicon)[rayson](/maintainers/rayson)

---

Top Contributors

[![rayson-x](https://avatars.githubusercontent.com/u/17398068?v=4)](https://github.com/rayson-x "rayson-x (22 commits)")

---

Tags

asynccoroutinephpphpasyncreactphpcoroutine

### Embed Badge

![Health badge](/badges/ant-framework-coroutine/health.svg)

```
[![Health](https://phpackages.com/badges/ant-framework-coroutine/health.svg)](https://phpackages.com/packages/ant-framework-coroutine)
```

###  Alternatives

[react/promise-timer

A trivial implementation of timeouts for Promises, built on top of ReactPHP.

34141.9M96](/packages/react-promise-timer)[clue/docker-react

Async, event-driven access to the Docker Engine API, built on top of ReactPHP.

113154.9k1](/packages/clue-docker-react)[badfarm/zanzara

Asynchronous PHP Telegram Bot Framework

2042.5k](/packages/badfarm-zanzara)[clue/reactphp-eventsource

Instant real-time updates. Lightweight EventSource client receiving live messages via HTML5 Server-Sent Events (SSE). Fast stream processing built on top of ReactPHP's event-driven architecture.

5818.5k3](/packages/clue-reactphp-eventsource)[recoil/react

Integrate Recoil with ReactPHP.

32274.4k12](/packages/recoil-react)[clue/multicast-react

Simple, event-driven multicast UDP message client and server for ReactPHP.

2569.0k3](/packages/clue-multicast-react)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
