PHP code example of thruster / packet-handler

1. Go to this page and download the library: Download thruster/packet-handler 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/ */

    

thruster / packet-handler example snippets


use Thruster\Component\EventLoop\EventLoop;
use Thruster\Component\Socket\SocketPair;
use Thruster\Component\PacketHandler\Packet;
use Thruster\Component\PacketHandler\PacketHandler;
use Thruster\Component\PacketHandler\StreamHandler;

class PingPacket extends Packet
{
    const NAME = 'ping';

    public function __construct()
    {
        parent::__construct(self::NAME);
    }
}

class PongPacket extends Packet
{
    const NAME = 'pong';

    private $pid;

    public function __construct()
    {
        $this->pid = posix_getpid();

        parent::__construct(self::NAME);
    }

    /**
     * @return int
     */
    public function getPid()
    {
        return $this->pid;
    }
}

$loop = new EventLoop();

$socketPair = new SocketPair($loop);
$socketPair->create();

$packetHandler = new PacketHandler();
$packetHandler->addHandler(PingPacket::NAME, function (PingPacket $packet) {
    $packet->getStreamHandler()->send(new PongPacket());
});

$packetHandler->addHandler(PongPacket::NAME, function (PongPacket $packet) {
    echo posix_getpid() . ': Received PONG from ' . $packet->getPid() . PHP_EOL;
});

if (pcntl_fork() > 0) {
    $connection = $socketPair->useLeft();

    $packetHandler->addProvider(new StreamHandler($connection));

    $loop->addPeriodicTimer(2, function () use ($packetHandler) {
        $packetHandler->dispatch(new PingPacket());
    });

    $loop->run();

} else {
    $loop->afterFork();

    $connection = $socketPair->useRight();

    $packetHandler->addProvider(new StreamHandler($connection));

    $loop->run();
}