Initial commit
This commit is contained in:
54
src/Interop/Channel/StreamChannel.php
Normal file
54
src/Interop/Channel/StreamChannel.php
Normal file
@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace NoccyLabs\Ipc\Interop\Channel;
|
||||
|
||||
|
||||
class StreamChannel implements ChannelInterface
|
||||
{
|
||||
protected $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;
|
||||
|
||||
$this->isOpen();
|
||||
}
|
||||
|
||||
public function send($data)
|
||||
{
|
||||
fwrite($this->stream, json_encode($data)."\0");
|
||||
}
|
||||
|
||||
public function receive()
|
||||
{
|
||||
$buf = fread($this->stream, 8192);
|
||||
|
||||
return json_decode(rtrim($buf, "\0"));
|
||||
}
|
||||
|
||||
public function isOpen(): bool
|
||||
{
|
||||
return is_resource($this->stream);
|
||||
}
|
||||
|
||||
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])
|
||||
];
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user