PHP code example of tianhe1986 / fatbinarybuffer

1. Go to this page and download the library: Download tianhe1986/fatbinarybuffer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tianhe1986 / fatbinarybuffer example snippets



use Workerman\Worker;
use Workerman\Protocols\Websocket;
use FatBinaryBuffer\FatBinaryBuffer;

$ws_worker = new Worker("websocket://0.0.0.0:13001");

// 4 processes
$ws_worker->count = 4;

$ws_worker->onConnect = function($connection)
{
    $connection->onWebSocketConnect = function($connection , $http_header)
    {
        $connection->websocketType = Websocket::BINARY_TYPE_ARRAYBUFFER;
    };
};

$ws_worker->onMessage = function($connection, $data)
{
    $socketData = new FatBinaryBuffer(false);
    $socketData->setBuffer($data);
    $opcode = $socketData->readUInt32();
    echo $opcode."\n";
    echo $socketData->readUInt32()."\n";
    echo $socketData->readUInt32()."\n";
    if ($opcode === 21102) {
        echo $socketData->readUInt32()."\n";
        $newData = new FatBinaryBuffer(false);
        $newData->writeUInt32(21103);
        $newData->writeUInt32(16);
        $newData->writeUInt32(11);
        $newData->writeUInt32(777);
        $connection->send($newData->getBuffer());
    } else if ($opcode === 21104) {
        $len = $socketData->readUShort();
        echo "string len ".$len."\n";
        echo $socketData->readStringByLength($len)."\n";
        echo $socketData->readChar()."\n";
        echo $socketData->readUShort()."\n";
        echo $socketData->readInt32()."\n";
        echo $socketData->readStringByLength(5)."\n";
    }
};
Worker::runAll();