This commit is contained in:
Daniil Gentili 2023-09-01 22:19:00 +02:00
parent caa661d74f
commit 1fe632bfb3
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
3 changed files with 27 additions and 6 deletions

View File

@ -8,4 +8,17 @@ Usage:
```bash
composer require danog/stun
```
```
And then:
```php
<?php
use danog\Stun\StunClient;
require 'vendor/autoload.php';
$stun = new StunClient("stun.l.google.com:19302");
var_dump($stun->bind());
```

View File

@ -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());
$stun = new StunClient("stun.l.google.com:19302");
var_dump($stun->bind());

View File

@ -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;
}
}