OpenSwoole\Coroutine\Http\Client->upgrade(...)

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

Declaration

<?php OpenSwoole\Coroutine\Http\Client->upgrade(string $path): bool

Parameters

path

Set the URL path to upgrade. For example /user/account or /index.php. Only set the path here not the protocol or domain name like http://domain.

Return

Success

When the client successfully upgrades the connection to a WebSocket connection true is returned.

Failure

If the upgrade fails, false is returned and you should check $client->errCode to see what went wrong.


Description

Upgrade the HTTP request to be a websocket.

Sometimes when the WebSocket upgrade is successful but the remote server may reject the connection during the handshake phase. Make sure that the HTTP status code is 101 and not 200 or 403. A status code of 101 means the connection is switching protocols.

Once a successful WebSocket upgrade takes place you will be able to use the push() method. You can also use recv() to receive messages as well.

Note: Using upgrade will enable coroutine scheduling to take place while waiting.


Example

<?php
use OpenSwoole\Coroutine\HTTP\Client;

co::run(function()
{
    $client = new Co\http\Client("127.0.0.1", 9501);

    $ret = $client->upgrade("/");

    if($ret)
    {
        while(true)
        {
            $client->push("Hello World!");
            var_dump($client->recv());
            Co\System::sleep(5);
        }
    }
});
Last updated on September 1, 2022