55 lines
1.6 KiB
PHP
55 lines
1.6 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
/**
|
||
|
|
* This example demonstrates upgrading a ProtocolStream to use a different protocol
|
||
|
|
* than initially configured with.
|
||
|
|
*
|
||
|
|
* Run the example and try entering some things such as:
|
||
|
|
* hello world
|
||
|
|
* foo "bar baz"
|
||
|
|
* and finally:
|
||
|
|
* upgrade
|
||
|
|
* After the upgrade command, it will only respond to JSON data:
|
||
|
|
* {"foo":"bar"}
|
||
|
|
*
|
||
|
|
*/
|
||
|
|
|
||
|
|
use NoccyLabs\React\Protocol\Json\JsonProtocol;
|
||
|
|
use NoccyLabs\React\Protocol\Line\LineProtocol;
|
||
|
|
use NoccyLabs\React\Protocol\ProtocolStream;
|
||
|
|
use React\Stream\CompositeStream;
|
||
|
|
use React\Stream\ReadableResourceStream;
|
||
|
|
use React\Stream\WritableResourceStream;
|
||
|
|
|
||
|
|
require_once __DIR__."/../vendor/autoload.php";
|
||
|
|
|
||
|
|
$stdin = new ReadableResourceStream(STDIN);
|
||
|
|
$stdout = new WritableResourceStream(STDOUT);
|
||
|
|
$stdio = new CompositeStream($stdin, $stdout);
|
||
|
|
|
||
|
|
$textProto = new LineProtocol(
|
||
|
|
beforePackCb: function (array $msg): array {
|
||
|
|
$out = [];
|
||
|
|
$cmd = array_shift($msg);
|
||
|
|
$out = [ $cmd, ...array_map("json_encode", $msg) ];
|
||
|
|
return $out;
|
||
|
|
}
|
||
|
|
);
|
||
|
|
$jsonProto = new JsonProtocol(
|
||
|
|
frameSeparator: "\n"
|
||
|
|
);
|
||
|
|
|
||
|
|
$stream = new ProtocolStream($stdio, $textProto);
|
||
|
|
$stream->on("message", function (array $msg) use ($stream, $jsonProto) {
|
||
|
|
if (array_is_list($msg)) {
|
||
|
|
if (reset($msg) == 'upgrade') {
|
||
|
|
$stream->send([ 'OK', 'Upgrading to JSON protocol']);
|
||
|
|
$stream->upgrade($jsonProto);
|
||
|
|
$stream->send([ 'info' => 'Now using JSON proto' ]);
|
||
|
|
} else {
|
||
|
|
$stream->send([ 'echo', json_encode($msg)]);
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
$stream->send([ 'echo' => $msg ]);
|
||
|
|
}
|
||
|
|
});
|