OpenSwoole Hook Sockets

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

The OpenSwoole\Runtime::HOOK_SOCKETS flag will enable coroutine support for PHP socket_* functions. Support was added in OpenSwoole v4.6.0.

You have to install OpenSwoole core library with composer require openswoole\core to use this hook.

More information on sockets can be found here.

Example

<?php

Co::set(['hook_flags' => OpenSwoole\Runtime::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);
    }
});
Last updated on September 20, 2022