Swoole\Coroutine\Http\Client->push(...)

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


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Coroutine\Http\Client->push(mixed $data, int $opcode = WEBSOCKET_OPCODE_TEXT, int $flags = SWOOLE_WEBSOCKET_FLAG_FIN): bool

Parameters

data

The data to be transmitted to the remote server. The default data format is UFT-8 tex.

opcode

The opcode to be sent to the remote websocket server. Default is WEBSOCKET_OPCODE_TEXT. Use WEBSOCKET_OPCODE_BINARY to send in binary or other formats.

flags

Set any WebSocket connection flags, see description for more details.

Return

Success

When the client successfully pushes data to the write buffer, this method returns true immediately without blocking during sending.

Failure

If the push fails, false will be returned, check $client->errCode to see what went wrong. Make sure you have given a valid OpCode.


Description

Send data/message to the remote WebSocket server.

This push() method does not block, it returns immediately after sending to the write buffer, no coroutine scheduling will take place when using this method.

Important: You must first upgrade() the connection first and this must pass the handshake stage and return HTTP status code 101 to be successful.

Since v4.2.0 the $data parameter can also be a Swoole\WebSocket\Frame object as well.

When setting the WebSocket OpCode, if it is not a valid format, this method will return false and you will be given the error message opcode max 10 for invalid WebSocket OpCode.


WebSocket Flags

By default SWOOLE_WEBSOCKET_FLAG_FIN is set but you may use SWOOLE_WEBSOCKET_FLAG_COMPRESS to enable compression on this push() operation.


Return Values

When the push() operation works successfully, true is returned. However, on failure there are a few error messages to consider:

  • 8502: Invalid OpCode given.
  • 8503: No connection to the server or the connection has been closed.
  • 8504: Handshake failed.

If you get no error code when checking $client->errCode it means the connection does not exist, has been closed or the connection has not been upgraded to a WebSocket connection.


Example

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

Co\run(function()
{
    $client = new Client('127.0.0.1', 80);

    $client->setHeaders([
        'Host' => "localhost",
        "User-Agent" => 'Chrome/49.0.2587.3',
        'Accept' => 'text/html,application/xhtml+xml,application/xml',
        'Accept-Encoding' => 'gzip',
    ]);

    $client->set(['timeout' => 1]);

    // Convert to using the WebSocket protocol for this path
    $client->upgrade('/');

    // Sending data using the WebSocket connection
    $client->push("websocket data\n");

    // Receiving from the WebSocket connection
    var_dump($client->recv());

    $client->close();
});
Last updated on August 31, 2022