WebSocket Compression Example

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

Description

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 OpenSwoole\WebSocket\Server::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.

Frame Compression Example

You can enable WebSocket Frame Compression and use it on a specific data frame.

OpenSwoole Server

<?php

use OpenSwoole\WebSocket\Frame;
use OpenSwoole\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 OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_COMPRESS flag to compress the frame
    $server->push(
        $frame->fd,
        'Hello World, from OpenSwoole Server!',
        OpenSwoole\WebSocket\Server::WEBSOCKET_OPCODE_TEXT,
        OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN | OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_COMPRESS
    );
});
$server->start();

OpenSwoole Client

<?php

use \OpenSwoole\Coroutine\Http\Client;

$cli = Client('127.0.0.1', 9501);

$cli->set(['websocket_compression' => true]);

$cli->upgrade('/');

// Using the OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_COMPRESS flag to compress the frame
$cli->push(
    'Hello World, from Swoole Client!',
    OpenSwoole\WebSocket\Server::WEBSOCKET_OPCODE_TEXT,
    OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_FIN | OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_COMPRESS
);

See the push() method documentation on where to specifically use the OpenSwoole\WebSocket\Server::WEBSOCKET_FLAG_COMPRESS flag, it is part of the int $flags parameter.

Last updated on September 20, 2022