PHP code example of lynnfly / hyperf-gateway-worker
1. Go to this page and download the library: Download lynnfly/hyperf-gateway-worker 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/ */
lynnfly / hyperf-gateway-worker example snippets
return [
// 业务进程
'business' => [
// 是否启用
'enable' => true,
// ...
// 事件处理类
'event_handler' => LynnFly\GatewayWorker\EventHandler::class,
// ...
],
// ...
];
class EventHandler
{
public static function onWebSocketConnect(string $clientId, array $body): void
{
var_dump(__METHOD__);
echo "onWebSocketConnect clientId: $clientId\n";
}
public static function onConnect(string $clientId): void
{
var_dump(__METHOD__);
echo "onConnect clientId: $clientId\n";
$uid = mt_rand(1111, 9999);
GatewaySession::set('uid', $uid); // or $_SESSION['uid'] = $uid;
Gateway::sendToCurrentClient("Hello $uid, clientId: $clientId\n");
}
public static function onMessage(string $clientId, string $body): void
{
var_dump(__METHOD__);
echo "onMessage clientId: $clientId, body: $body\n";
$uid1 = GatewaySession::get('uid');
$uid2 = $_SESSION['uid'] ?? null;
Gateway::sendToCurrentClient("Hi,$uid1:$uid2\nReceived: $body\n");
}
public static function onClose(string $clientId): void
{
var_dump(__METHOD__);
echo "onClose clientId: $clientId\n";
}
public static function onException(Throwable $throwable): void
{
var_dump(__METHOD__, $throwable->getMessage());
}
}
bash
php bin/hyperf.php vendor:publish lynnfly/hyperf-gateway-worker
bash
php bin/hyperf.php gateway:worker -r -g start