在laravel框架中优雅使用swoole扩展

swoole官网

创建command

这里我们用laravel的artisan命令来启动...

php artisan make:command GameJoinRoom

command代码

namespace App\Console\Commands;

use swoole_websocket_server;
use Illuminate\Console\Command;

class GameJoinRoom extends Command
{

    protected $signature = 'game:join-room {action}';
    protected $description = '加入房间';
    public function __construct ()
    {
        parent::__construct();
    }
    public function handle ()
    {
        $action = $this->argument('action');
        //提供三个命令
        if (!in_array($action, ['start', 'stop', 'restart'])) {
            $this->error('参数错误!!!');
            exit;
        }
        switch ($action) {
            case 'start':
                $this->info('started');
                $this->start();
                break;
        }
    }

    public function start ()
    {

        $this->server = new swoole_websocket_server("0.0.0.0", 10006);

        $handle = app()->make(\App\Game\GameJoinRoom::class);
        // 这里我们把事件监听到GameJoinRoom类上
        $this->server->on('open', array($handle, 'onOpen'));
        $this->server->on('message', array($handle, 'onMessage'));
        $this->server->on('close', array($handle, 'onClose'));

        $this->server->start();
    }
}

启动服务

php artisan game:join-room start

服务常驻

这里可以用swoole自带daemonize设置来常驻

$this->server->set([
    'daemonize' => 1
]);

不过我个人喜欢用Supervisor来常驻