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
It is possible to compress data frames when pushing WebSocket data to the client, the client must support compression in order to receive such a request. If you enable WebSocket data compression, you can use the SWOOLE_WEBSOCKET_FLAG_COMPRESS
flag to compress a specific data frame.
The example below is a good guide on how WebSocket compression works but you must also enable it via the websocket_compression
configuration option before the server starts up.
Once enabled the server will give time specifically to check if compression is supported in accordance with WebSocket RFC-7692.
You can enable WebSocket Frame Compression and use it on a specific data frame.
Swoole Server
<?php
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
$server = new Server('127.0.0.1', 9501);
$server->set(['websocket_compression' => true]);
$server->on('Message', function(Server $server, Frame $frame)
{
// Using the SWOOLE_WEBSOCKET_FLAG_COMPRESS flag to compress the frame
$server->push(
$frame->fd,
'Hello World, from Swoole Server!',
SWOOLE_WEBSOCKET_OPCODE_TEXT,
SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
);
});
$server->start();
Swoole Client
<?php
use \Swoole\Coroutine\Http\Client;
$cli = Client('127.0.0.1', 9501);
$cli->set(['websocket_compression' => true]);
$cli->upgrade('/');
// Using the SWOOLE_WEBSOCKET_FLAG_COMPRESS flag to compress the frame
$cli->push(
'Hello World, from Swoole Client!',
SWOOLE_WEBSOCKET_OPCODE_TEXT,
SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
);
See the push()
method documentation on where to specifically use the SWOOLE_WEBSOCKET_FLAG_COMPRESS
flag, it is part of the int $flags
parameter.