PHP code example of tourze / workerman-rfc3489

1. Go to this page and download the library: Download tourze/workerman-rfc3489 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tourze / workerman-rfc3489 example snippets


use Tourze\Workerman\RFC3489\Message\MessageFactory;
use Tourze\Workerman\RFC3489\Message\ErrorCode;

// Create a Binding request
$request = MessageFactory::createBindingRequest();

// Create a Binding response
$response = MessageFactory::createBindingResponse(
    $request->getTransactionId(),
    '192.168.1.100',
    12345
);

// Create an error response
$errorResponse = MessageFactory::createBindingErrorResponse(
    $request->getTransactionId(),
    ErrorCode::SERVER_ERROR,
    'Internal server error'
);

use Tourze\Workerman\RFC3489\Protocol\StunClient;

// Create STUN client with server address and port
$client = new StunClient('stun.l.google.com', 19302);

// Discover public IP address
try {
    [$publicIp, $publicPort] = $client->discoverPublicAddress();
    echo "Public IP: {$publicIp}:{$publicPort}";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    $client->close();
}

use Tourze\Workerman\RFC3489\Protocol\Server\StunServerFactory;

// Create STUN server factory
$factory = new StunServerFactory();

// Create server listening on port 3478
$server = $factory->createWorkermanServer('0.0.0.0', 3478);

// Start server
$server->start();

use Tourze\Workerman\RFC3489\Protocol\NatTypeDetector;

// Create NAT detector with STUN server details
$detector = new NatTypeDetector('stun.l.google.com', 19302);

// Detect NAT type
$natType = $detector->detect();
echo "NAT Type: " . $natType->value;
echo "Description: " . $natType->getDescription();
echo "Supports P2P: " . ($natType->isSupportP2P() ? 'Yes' : 'No');

use Tourze\Workerman\RFC3489\Protocol\StunClient;
use Psr\Log\LoggerInterface;

// Create client with custom timeout and logger
$client = new StunClient(
    'stun.l.google.com', 
    19302,
    null,           // transport (null for default UDP)
    $logger,        // PSR-3 logger instance
    5000           // timeout in milliseconds
);

use Tourze\Workerman\RFC3489\Protocol\Server\Handler\StunMessageHandlerInterface;
use Tourze\Workerman\RFC3489\Message\StunMessage;

class CustomBindingHandler implements StunMessageHandlerInterface
{
    public function handleMessage(StunMessage $request, string $clientIp, int $clientPort): ?StunMessage
    {
        // Custom handling logic for STUN requests
        // Return response message or null if no response needed
        return $response;
    }
}