多个搭建同单个,创建Command,Event,注意修改各个端口
<?php
namespace App\Console\Commands;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Illuminate\Console\Command;
use Workerman\Worker;
class Server extends Command
{
//php artisan ws start
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'ws {action} {--d}';
/**
* The console command description.
*
* @var string
*/
protected $description = '启动WS';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
public function handle()
{
global $argv;//定义全局变量
$arg = $this->argument('action');
$argv[0] = 'mp-server-ws';
$argv[1] = $arg;
$argv[2] = $this->option('d') ? '-d' : '';//该参数是以daemon(守护进程)方式启动
$this->start();
}
public function start()
{
$this->startGateWay();
$this->startBusinessWorker();
$this->startRegister();
//注意一定要指定pidFile,不然会提示already running,无法运行
Worker::$pidFile = 'server.pid';
Worker::runAll();
}
private function startBusinessWorker()
{
$worker = new BusinessWorker();
$worker->name = 'BusinessWorker';
$worker->count = 1;
$worker->registerAddress = '127.0.0.1:1237';
$worker->eventHandler = \App\ServerWS\Events::class;
}
private function startGateWay()
{
$gateway = new Gateway("websocket://0.0.0.0:10002");
$gateway->name = 'Gateway';
$gateway->count = 1;
$gateway->lanIp = '127.0.0.1';
//官方建议startPort与其他的间隔大点
$gateway->startPort = 10000;
$gateway->pingInterval = 30;
$gateway->pingNotResponseLimit = 0;
$gateway->pingData = '{"type":"@heart@", "from": "server"}';
$gateway->registerAddress = '127.0.0.1:1237';
}
private function startRegister()
{
new Register('text://0.0.0.0:1237');
}
}
然后在使用时,指定Gateway
Gateway::$registerAddress = '127.0.0.1:1237';
Gateway::sendToAll("some message");
|