laravel+GatewayWorker

5 阅读1分钟
<?php

namespace App\Console\Commands;

use App\Events\MsgEvent;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Illuminate\Console\Command;
use Workerman\Worker;

class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test {action} {--d}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '123456';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        global $argv;
        $action = $this->argument('action');
        if (!in_array($action, ['start', 'stop', 'status'])) {
            $this->error('Action Error');
            exit;
        }
        $argv[0] = 'Test';
        $argv[1] = $action;
        $argv[2] = $this->option('d') ? '-d' : '';

        Worker::$pidFile = storage_path('app/workerman.pid');

        $register = new Register('text://127.0.0.1:1236');

        $gateway = new Gateway("tcp://0.0.0.0:8282");
        $gateway->name = 'YourAppGateway';
        $gateway->count = 2;
        $gateway->lanIp = '127.0.0.1';
        $gateway->startPort = 2900;
        $gateway->registerAddress = '127.0.0.1:1236';
        $gateway->router = function ($worker_connections) {
            return $worker_connections[array_rand($worker_connections)];
        };

        $worker = new BusinessWorker();
        $worker->name = 'YourAppBusinessWorker';
        $worker->count = 1;
        $worker->registerAddress = '127.0.0.1:1236';
        $worker->eventHandler = MsgEvent::class;

        Worker::runAll();
    }
}

<?php

namespace App\Events;


class MsgEvent
{


    public static function onConnect($client_id)
    {
        echo 'onConnect ' . $client_id . PHP_EOL;
    }

    public static function onMessage($client_id, $message)
    {
        echo 'onMessage ' . $message . PHP_EOL;
    }


    public static function onClose($client_id)
    {
        echo 'onClose ' . $client_id . PHP_EOL;
    }
}