OpenSwoole Hook TCP

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

The OpenSwoole\Runtime::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' => OpenSwoole\Runtime::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' => OpenSwoole\Runtime::HOOK_TCP]);

$http = new OpenSwoole\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