thruster/packet-handler

Thruster PacketHandler Component

1.0.0 2016-05-25 13:31 UTC

This package is auto-updated.

Last update: 2024-12-14 03:33:54 UTC


README

[Latest Version] (https://github.com/ThrusterIO/packet-handler/releases) [Software License] (LICENSE) [Build Status] (https://travis-ci.org/ThrusterIO/packet-handler) [Code Coverage] (https://scrutinizer-ci.com/g/ThrusterIO/packet-handler) [Quality Score] (https://scrutinizer-ci.com/g/ThrusterIO/packet-handler) [Total Downloads] (https://packagist.org/packets/thruster/packet-handler)

[Email] (mailto:team@thruster.io)

The Thruster PacketHandler Component.

Install

Via Composer

$ composer require thruster/packet-handler

Usage

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();
}

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CONDUCT for details.

License

Please see License File for more information.