Coroutine Server

Coroutine Server are the Server created within a coroutine context programmatically.

Multiple Coroutine Servers can be created within one process.

It is different and not the replacement of the Swoole\Server with callbacks.

Methods

  • Swoole\Coroutine\Server->__construct
  • Swoole\Coroutine\Server->set
  • Swoole\Coroutine\Server->handle
  • Swoole\Coroutine\Server->start
  • Swoole\Coroutine\Server->shutdown

    Example

    <?php
    
    use Swoole\Coroutine\Server;
    use Swoole\Coroutine\Server\Connection;
    
    Co\run(function() {
    
        go(function () {
            $server = new Server('0.0.0.0', 9501, false);
    
            $server->handle(function (Connection $conn) {
                while (true) {
    
                    $data = $conn->recv();
                    if (!$data) {
                        break;
                    }
                    $conn->send("hello $data");
                }
                $conn->close();
            });
            echo "Start TCP server :9501\n";
            $server->start();
        });
    
        go(function () {
            $server = new Server('0.0.0.0', 9502, false);
    
            $server->handle(function (Connection $conn) {
                while (true) {
    
                    $data = $conn->recv();
                    if (!$data) {
                        break;
                    }
                    $conn->send("hello $data");
                }
                $conn->close();
            });
            echo "Start TCP server :9502\n";
            $server->start();
        });
    
    });
    
    Swoole\Coroutine\Server::__construct(string $host, int $port = 0, bool $ssl = false, bool $reuse_port = false)
    Swoole\Coroutine\Server->set(array $options)

    Example:

    <?php
    
    use Swoole\Coroutine\Server;
    
    use function Co\run;
    
    run(function () {
        $server = new Server('127.0.0.1', 9501, true);
        $server->set([
            'open_ssl' => true,
            'open_eof_check' => true,
            'open_eof_split' => true,
            'package_eof' => true,
            'open_mqtt_protocol' => true,
            ...
        ]);
    });
    
    Swoole\Coroutine\Server->handle(callable $func)

    Handle the accepted connection.

    Swoole\Coroutine\Server->start()

    Start the coroutine server.

    Swoole\Coroutine\Server->shutdown()

    Stop the coroutine server.