2017-06-23 07:34:11 +02:00
|
|
|
<?php
|
|
|
|
|
2017-06-27 18:30:28 +02:00
|
|
|
namespace Amp\Dns\Internal;
|
2017-06-23 07:34:11 +02:00
|
|
|
|
2019-01-04 18:20:52 +01:00
|
|
|
use Amp\Dns\DnsException;
|
2017-06-23 07:34:11 +02:00
|
|
|
use Amp\Promise;
|
|
|
|
use Amp\Success;
|
|
|
|
use LibDNS\Decoder\DecoderFactory;
|
|
|
|
use LibDNS\Encoder\EncoderFactory;
|
|
|
|
use LibDNS\Messages\Message;
|
|
|
|
use function Amp\call;
|
|
|
|
|
2017-06-23 21:07:59 +02:00
|
|
|
/** @internal */
|
2017-06-27 17:47:57 +02:00
|
|
|
class UdpSocket extends Socket {
|
2017-06-23 09:24:26 +02:00
|
|
|
/** @var \LibDNS\Encoder\Encoder */
|
2017-06-23 07:34:11 +02:00
|
|
|
private $encoder;
|
|
|
|
|
2017-06-23 09:24:26 +02:00
|
|
|
/** @var \LibDNS\Decoder\Decoder */
|
2017-06-23 07:34:11 +02:00
|
|
|
private $decoder;
|
|
|
|
|
|
|
|
public static function connect(string $uri): Promise {
|
|
|
|
if (!$socket = @\stream_socket_client($uri, $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT)) {
|
2019-01-04 18:20:52 +01:00
|
|
|
throw new DnsException(\sprintf(
|
2017-06-23 07:34:11 +02:00
|
|
|
"Connection to %s failed: [Error #%d] %s",
|
|
|
|
$uri,
|
|
|
|
$errno,
|
|
|
|
$errstr
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
return new Success(new self($socket));
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function __construct($socket) {
|
|
|
|
parent::__construct($socket);
|
|
|
|
|
|
|
|
$this->encoder = (new EncoderFactory)->create();
|
|
|
|
$this->decoder = (new DecoderFactory)->create();
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function send(Message $message): Promise {
|
|
|
|
$data = $this->encoder->encode($message);
|
|
|
|
return $this->write($data);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function receive(): Promise {
|
|
|
|
return call(function () {
|
|
|
|
$data = yield $this->read();
|
|
|
|
|
|
|
|
if ($data === null) {
|
2019-01-04 18:20:52 +01:00
|
|
|
throw new DnsException("Reading from the server failed");
|
2017-06-23 07:34:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return $this->decoder->decode($data);
|
|
|
|
});
|
|
|
|
}
|
2017-06-23 12:49:16 +02:00
|
|
|
|
|
|
|
public function isAlive(): bool {
|
|
|
|
return true;
|
|
|
|
}
|
2017-06-23 09:24:26 +02:00
|
|
|
}
|