OpenSwoole Hook TCP

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

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

This includes:

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

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.

Last updated on August 31, 2022