Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
<?php Swoole\Coroutine\Http\Client->push(mixed $data, int $opcode = WEBSOCKET_OPCODE_TEXT, int $flags = SWOOLE_WEBSOCKET_FLAG_FIN): bool
The data to be transmitted to the remote server. The default data format is UFT-8 tex.
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.
Set any WebSocket connection flags, see description for more details.
When the client successfully pushes data to the write buffer, this method returns true
immediately without blocking during sending.
If the push fails, false
will be returned, check $client->errCode
to see what went wrong. Make sure you have given a valid OpCode.
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 aSwoole\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.
By default SWOOLE_WEBSOCKET_FLAG_FIN
is set but you may use SWOOLE_WEBSOCKET_FLAG_COMPRESS
to enable compression on this push()
operation.
When the push()
operation works successfully, true
is returned. However, on failure there are a few error messages to consider:
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.
<?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();
});