Swoole Hook Sockets

Notice: the documentation is suitable for PHP extension swoole until v4.7.1, we only support PHP extension openswoole from v4.7.1

The SWOOLE_HOOK_SOCKETS flag will enable coroutine support for PHP socket_* functions. Support was added in v4.6.0.

More information on sockets can be found here.

Example

<?php

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

Co\run(function()
{
    $address = '127.0.0.1';
    $port = 1234;

    // Create WebSocket
    $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
    socket_bind($server, $address, $port);
    socket_listen($server);

    $client = socket_accept($server);

    // Send messages into WebSocket in a loop
    while(true) 
    {
        sleep(1);
        $content = 'Now: ' . time();
        $response = chr(129) . chr(strlen($content)) . $content;
        socket_write($client, $response);
    }
});