PHP code example of ant-framework / coroutine

1. Go to this page and download the library: Download ant-framework/coroutine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ant-framework / coroutine example snippets




$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();



// 监听并绑定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);
        }
    });
});