PHP code example of tourze / workerman-chain-protocol
1. Go to this page and download the library: Download tourze/workerman-chain-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-chain-protocol example snippets
use Tourze\Workerman\ChainProtocol\ChainProtocol;
use Tourze\Workerman\ChainProtocol\Container;
use Workerman\Worker;
// Setup your custom protocol classes that implement ProtocolInterface
Container::$decodeProtocols = [
MyProtocol1::class,
MyProtocol2::class,
// Add more protocols as needed
];
Container::$encodeProtocols = [
MyProtocol2::class,
MyProtocol1::class,
// The order matters for encoding (reverse of decoding)
];
// Setup logger if needed
Container::$logger = new MyLogger();
// Setup event dispatcher if needed
Container::$eventDispatcher = new MyEventDispatcher();
// Create a Workerman server with ChainProtocol
$worker = new Worker('tcp://0.0.0.0:8080');
$worker->protocol = ChainProtocol::class;
$worker->onMessage = function($connection, $data) {
// $data is already decoded through all protocols in the chain
// Process your business logic here
// Send a response, which will be encoded through all protocols in the chain
$connection->send('Your response');
};
Worker::runAll();
use Workerman\Protocols\ProtocolInterface;
use Workerman\Connection\ConnectionInterface;
class MyCustomProtocol implements ProtocolInterface
{
public static function input(string $buffer, ConnectionInterface $connection): int
{
// Return the length of a complete packet, or 0 if more data is needed
return strlen($buffer) >= 4 ? unpack('N', substr($buffer, 0, 4))[1] + 4 : 0;
}
public static function decode(string $buffer, ConnectionInterface $connection): string
{
// Remove the length header and return the actual data
return substr($buffer, 4);
}
public static function encode(mixed $data, ConnectionInterface $connection): string
{
// Add a length header to the data
return pack('N', strlen($data)) . $data;
}
}
use Symfony\Component\EventDispatcher\EventDispatcher;
use Tourze\Workerman\ChainProtocol\Event\ChainDataDecodedEvent;
use Tourze\Workerman\ChainProtocol\Container;
$eventDispatcher = new EventDispatcher();
$eventDispatcher->addListener(ChainDataDecodedEvent::class, function(ChainDataDecodedEvent $event) {
// Log or process decoded data
error_log('Data decoded: ' . $event->getBuffer());
});
Container::$eventDispatcher = $eventDispatcher;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Tourze\Workerman\ChainProtocol\Container;
$logger = new Logger('chain-protocol');
$logger->pushHandler(new StreamHandler('path/to/logfile.log', Logger::DEBUG));
Container::$logger = $logger;
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.