OpenSwoole\WebSocket\Server::unpack()

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

Declaration

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

Parameters

data

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

Return

If success, it returns OpenSwoole\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 OpenSwoole\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 = OpenSwoole\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 September 1, 2022