This library implements the NetString protocol and provides a NetStringReader, a NetStringWriter and a bidirectional NetStringConnection implementation for AMPHP.
This package can be installed as a Composer dependency on PHP 8.1 and later.
composer require imedge/protocol-netstring
<?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);
}
string(5) "Hello"
string(6) "world!"
<?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());
string(21) "5:Hello,1: ,6:World!,"
A NetStingConnection allows for bidirectional NetString communication.
<?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());
string(5) "Hello"
string(6) "world!"
string(6) "3:Hi!"