Swoole\WebSocket\Server::unpack()

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


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\WebSocket\Server::unpack(string $data): Swoole\WebSocket\Frame|false

Parameters

data

The data/message content you want to unpack. Parses the WebSocket data frame content.

Return

If success, it returns Swoole\WebSocket\Frame, otherwise it returns false

Description

Unpack data from a WebSocket Frame.

If the parsing fails, then false will be returned, otherwise you will receive a Swoole\WebSocket\Frame object with unpacked data.

WebSocket Frame OpCodes

You can set these OpCodes

  • WEBSOCKET_OPCODE_TEXT = 1: String data
  • WEBSOCKET_OPCODE_BINARY = 2: Binary data
  • WEBSOCKET_OPCODE_PING = 3: Ping packet

Example

<?php

// Server setup...

$server->on('Receive', function($server, $fd, $threadId, $data)
{
    $dataFrame = Swoole\WebSocket\Server::unpack($data);

    if($dataFrame === false)
    {
        echo "Data failed to parse\n";
        $server->send($fd, "Parsing error with: $data\n\n");
    }

    echo "Data successfully parsed and received:\n";
    $server->send($fd, $dataFrame->data . "\n\n");
});

// ...
Last updated on August 31, 2022