PHP code example of tourze / workerman-rate-limit-protocol

1. Go to this page and download the library: Download tourze/workerman-rate-limit-protocol 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-rate-limit-protocol example snippets




use Tourze\Workerman\RateLimitProtocol\TrafficRateLimitProtocol;
use Workerman\Worker;
use Workerman\Connection\TcpConnection; // Ensure TcpConnection is imported if used

otocol = TrafficRateLimitProtocol::class;
TrafficRateLimitProtocol::setDefaultLimit(1024 * 1024); // 1MB/s

$worker->onConnect = function(TcpConnection $connection) { // Type hint connection for clarity
    echo "New connection from {$connection->getRemoteAddress()}\n";

    // Optional: Set a different rate limit for this specific connection
    TrafficRateLimitProtocol::setConnectionLimit($connection, 2 * 1024 * 1024); // 2MB/s for this one
    echo "Set connection-specific limit to 2MB/s for {$connection->id}\n";
};

$worker->onMessage = function(TcpConnection $connection, $data) {
    // The protocol handles the rate limiting check in its input/encode methods.
    // Your application logic receives data only if it's within the limit.
    echo "Received message from {$connection->id}: {$data}\n";
    $connection->send('Server received: ' . $data);
};

$worker->onClose = function(TcpConnection $connection) {
    echo "Connection closed from {$connection->getRemoteAddress()}\n";
};

Worker::runAll();




use Tourze\Workerman\RateLimitProtocol\PacketRateLimitProtocol;
use Workerman\Worker;
use Workerman\Connection\TcpConnection;

rker = new Worker('tcp://0.0.0.0:8081');
$worker->protocol = PacketRateLimitProtocol::class;
PacketRateLimitProtocol::setDefaultLimit(100); // 100 packets/s

$worker->onConnect = function(TcpConnection $connection) {
    echo "New connection on 8081 from {$connection->getRemoteAddress()}\n";

    // Optional: Set a different packet rate limit for this connection
    PacketRateLimitProtocol::setConnectionLimit($connection, 200); // 200 packets/s for this one
    echo "Set connection-specific packet limit to 200/s for {$connection->id}\n";
};

$worker->onMessage = function(TcpConnection $connection, $data) {
    echo "Received message on 8081 from {$connection->id}: {$data}\n";
    $connection->send('Server received packet: ' . $data);
};

$worker->onClose = function(TcpConnection $connection) {
    echo "Connection closed on 8081 from {$connection->getRemoteAddress()}\n";
};

Worker::runAll();