91 lines
1.8 KiB
PHP
91 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\Ipc\Interop\Channel;
|
|
|
|
/**
|
|
* Channel based on streams
|
|
*
|
|
*/
|
|
class StreamChannel implements ChannelInterface
|
|
{
|
|
protected $stream;
|
|
|
|
/**
|
|
* Constructor
|
|
*
|
|
* @param resource|string $stream
|
|
*/
|
|
public function __construct($stream)
|
|
{
|
|
if (!is_resource($stream)) {
|
|
if (!is_string($stream)) {
|
|
throw new \LogicException("Invalid stream");
|
|
}
|
|
$stream = stream_socket_client($stream, $errno, $errstr);
|
|
if (!$stream) {
|
|
throw new \RuntimeException(sprintf("%d %s", $errno, $errstr));
|
|
}
|
|
}
|
|
|
|
$this->stream = $stream;
|
|
|
|
stream_set_blocking($stream, false);
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*
|
|
* @param mixed $data
|
|
* @return bool
|
|
*/
|
|
public function send($data):bool
|
|
{
|
|
$json = json_encode($data) . "\0";
|
|
$ret = @fwrite($this->stream, $json, strlen($json));
|
|
if (false === $ret) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function receive()
|
|
{
|
|
$buf = fread($this->stream, 8192);
|
|
if (!$buf) {
|
|
return false;
|
|
}
|
|
|
|
return json_decode(rtrim($buf, "\0"), true);
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*
|
|
* @return boolean
|
|
*/
|
|
public function isOpen(): bool
|
|
{
|
|
return is_resource($this->stream);
|
|
}
|
|
|
|
/**
|
|
* Create a pair of connected StreamChannel instances
|
|
*
|
|
* @return StreamChannel[]
|
|
*/
|
|
public static function createPair()
|
|
{
|
|
$fd = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
|
|
|
|
return [
|
|
new StreamChannel($fd[0]),
|
|
new StreamChannel($fd[1])
|
|
];
|
|
}
|
|
|
|
} |