Swoole Hook TCP

The SWOOLE_HOOK_TCP flag will enable coroutine support for TCP sockets and streams.

This includes:

Since v4.1.0 Swoole began to support TCP sockets and streams, you can use native Redis and PDO classes when enabling this hook.

Quick Example

<?php

Co::set(['hook_flags' => SWOOLE_HOOK_TCP]);

Co\run(function() {

    for ($c = 100; $c--;) {

        go(function () {

            $redis = new Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->get('key');

        });

    }
});

Server Example

<?php

Co::set(['hook_flags' => SWOOLE_HOOK_TCP]);

$http = new Swoole\Http\Server("0.0.0.0", 9501);

$http->set(['enable_coroutine' => true]);

$http->on('request', function ($request, $response) {

      $redis = new Redis();
      $redis->connect('127.0.0.1', 6379);
      $redis->get('key');

});

$http->start();

Remember you don't need to create a coroutine context with Co\run() when running a server as one is created for you during a request.