imedge/protocol-netstring

Asynchronous NetString implementation for AMPHP

v0.4.0 2024-07-10 17:48 UTC

This package is auto-updated.

Last update: 2025-02-26 14:14:17 UTC


README

This library implements the NetString protocol and provides a NetStringReader, a NetStringWriter and a bidirectional NetStringConnection implementation for AMPHP.

Coding Standards Unit Tests Static Analysis PHPStan Level 9 Minimum PHP Version: 8.1 License: MIT Version

Installation

This package can be installed as a Composer dependency on PHP 8.1 and later.

composer require imedge/protocol-netstring

Usage

NetStringReader

Sample Code

<?php

use Amp\ByteStream\ReadableBuffer;
use IMEdge\Protocol\NetString\NetStringReader;

$netString = new NetStringReader(new ReadableBuffer('5:Hello,6:world!,'));
foreach ($netString->packets() as $packet) {
    var_dump($packet);
}

Output

string(5) "Hello"
string(6) "world!"

NetStringWriter

Sample Code

<?php

use Amp\ByteStream\WritableBuffer;
use IMEdge\Protocol\NetString\NetStringWriter;

$netString = new NetStringWriter($out = new WritableBuffer());
$netString->write('Hello');
$netString->write(' ');
$netString->write('World!');
$netString->close();
var_dump($out->buffer());

Output

string(21) "5:Hello,1: ,6:World!,"

NetStringConnection

A NetStingConnection allows for bidirectional NetString communication.

Sample Code

<?php

use Amp\ByteStream\ReadableBuffer;
use Amp\ByteStream\WritableBuffer;
use IMEdge\Protocol\NetString\NetStringConnection;

$netString = new NetStringConnection(new ReadableBuffer('5:Hello,6:world!,'), $out = new WritableBuffer());
$netString->write('Hi!');
foreach ($netString->packets() as $packet) {
    var_dump($packet);
}
$out->close();
var_dump($out->buffer());

Output

string(5) "Hello"
string(6) "world!"
string(6) "3:Hi!"