安装:
composer require workerman/gateway-worker
目录结构:
注意:startPort设置端口,是和BusinessWorker进行连接的本地端口。
GatewayWorker类的使用
创建项目目录,然后composer下载gateway,然后在项目根目录下创建
gateway.php
name = 'gateway';
$gate->count = 4;
$gate->onWorkerStart = function(){
echo 'gate way start'.PHP_EOL;
};
$gate->onWorkerStop = function(){
echo 'gate way stop'.PHP_EOL;
};
Worker::runAll();c
gateway和business必须在register中注册后, gateway才能向business发送数据
只有gateway能想business发送数据的时候,客户端才能连接gateway
name='business';
$business->count = 2;
$business->registerAddress = '127.0.0.1:6666';
// $business->eventHandler ='Events'; //Events.php
$business->onWorkerStart = function(){
echo "business start".PHP_EOL;
};
$business->onWorkerStop = function(){
echo "business stop".PHP_EOL;
};
Worker::runAll();
注意:gateway 和 business中注册的地址 必须 和 register类中的地址相同
gateway 是唯一暴露给客户端的接口,客户端要想连接gateway,必须保证
gateway,business,register三个进程都启动
当客户端发数据给gateway的时候,gateway将数据转发给business
business最终将数据转发给Events,events的onMessage 函数接收数据。
当Events被修改之后,至少要重启business.php ,否则修改不生效。
'xiaoming','userid'=>123]);
Gateway::sendToClient($client_id,'设置成功');
break;
case 'getSession':
$message = Gateway::getSession($client_id);
Gateway::sendToClient($client_id,$message);
break;
}
}
public static function onClose($client_id)
{
echo 'client_id...' . $client_id . 'on close' . PHP_EOL;
}
public static function onWorkerStop()
{
echo 'worker stop' . PHP_EOL;
}
public static function onWebSocketConnect($client_id, $data)
{
var_dump($data);
}
}
gate.php
require_once 'vendor/autoload.php';
// use Workerman\Worker;
use GatewayWorker\Gateway;
$gate = new Gateway('text://0.0.0.0:8880');
$gate->name = 'gateway';
$gate->count = 4;
$gate->registerAddress = '127.0.0.1:6666';
$gate->pingInterval = 10;
$gate->pingNotResponseLimit = 2;
$gate->pingData = 'ping';
$gate->onWorkerStart = function(){
echo 'gate way start'.PHP_EOL;
};
$gate->onWorkerStop = function(){
echo 'gate way stop'.PHP_EOL;
};
下载tp5.1框架
下载workerman 和gatewayWorker :composer require topthink/think-worker
启动gateway worker:php think worker:gateway ,自动同时启动gateway,business_worker,register
在config 的gateway_worker.php中可以配置gateway,business_worker,register
gateway的配置:
用户唯一需要关心的只是真正干活的Events,这个命名空间可以修改成我们需要的命名空间,然后我们自己实现Events.php即可