From 1fe632bfb3e32f784e25ce6febc7de465520639e Mon Sep 17 00:00:00 2001 From: Daniil Gentili Date: Fri, 1 Sep 2023 22:19:00 +0200 Subject: [PATCH] Improve --- README.md | 15 ++++++++++++++- bind.php | 4 ++-- src/StunClient.php | 14 +++++++++++--- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 1065b7f..8840d94 100644 --- a/README.md +++ b/README.md @@ -8,4 +8,17 @@ Usage: ```bash composer require danog/stun -``` \ No newline at end of file +``` + +And then: + +```php +bind()); +``` diff --git a/bind.php b/bind.php index 8396b7d..6847819 100644 --- a/bind.php +++ b/bind.php @@ -4,5 +4,5 @@ use danog\Stun\StunClient; require 'vendor/autoload.php'; -$stun = new StunClient("udp://stun.l.google.com:19302"); -var_dump($stun->bind()); \ No newline at end of file +$stun = new StunClient("stun.l.google.com:19302"); +var_dump($stun->bind()); diff --git a/src/StunClient.php b/src/StunClient.php index 571cc5b..fb7f742 100644 --- a/src/StunClient.php +++ b/src/StunClient.php @@ -5,6 +5,7 @@ namespace danog\Stun; use Amp\ByteStream\BufferedReader; use Amp\ByteStream\ReadableBuffer; use Amp\Socket\Socket; +use Webmozart\Assert\Assert; use function Amp\Socket\connect; @@ -21,15 +22,22 @@ final class StunClient public function __construct( private string $endpoint ) { - $this->socket = connect($endpoint); + $this->socket = connect("udp://$endpoint"); + } + + public function __destruct() + { + $this->socket->close(); } /** @no-named-arguments */ public function bind(Attribute ...$attributes): Message { - $msg = new Message(MessageMethod::BINDING, MessageClass::REQUEST, $attributes, \random_bytes(12)); + $msg = new Message(MessageMethod::BINDING, MessageClass::REQUEST, $attributes, $id = \random_bytes(12)); $msg->write($this->socket); $read = new ReadableBuffer($this->socket->read()); - return Message::read(new BufferedReader($read)); + $msg = Message::read(new BufferedReader($read)); + Assert::eq($msg->transactionId, $id); + return $msg; } }