Laravel使用Command引導啟動 workerman(websocket)

aba66發表於2021-10-30

1、安裝workerman

composer require workerman/workerman

2、建立workerman啟動檔案

php artisan make:command Workerman

修改Workerman檔案

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;

class Workerman extends Command
{
    protected $websocket;
    /**
     * 命令名稱
     *
     * @var string
     */
    protected $signature = 'workerman:websocket {action} {--daemonize}';
    /**
     * 說明描述
     *
     * @var string
     */
    protected $description = 'workerman websocket';
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        global $argv;
        $action=$this->argument('action');
        $argv[0]='workerman:websocket';
        $argv[1]=$action;
        $argv[2]=$this->option('daemonize')?'-d':'';
        $ws_worker = new Worker('websocket://0.0.0.0:2000');
        $ws_worker->onMessage=function($connection,$data){
            $connection->send('laravel workerman hello world');
        };
        Worker::runAll();
    }
}

3、註冊啟動檔案

在app/Console/Kernel.php中新增以下程式碼

    protected $commands = [
        //
        Commands\Workerman::class
    ];

4、命令列啟動workerman

php artisan workerman:websocket start

5、啟動成功效果

Workerman[workerman:websocket] start in DEBUG mode
------------------------------------------- WORKERMAN --------------------------------------------
Workerman version:4.0.22          PHP version:7.4.0
-------------------------------------------- WORKERS ---------------------------------------------
proto   user            worker          listen                      processes    status           
tcp     root            none            websocket://0.0.0.0:2000    1             [OK]            
--------------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.

注意事項

上述環境在Linux下執行,如果在win下會出現無法監聽,效果如下

----------------------- WORKERMAN -----------------------------
Workerman version:4.0.22          PHP version:7.4.3
------------------------ WORKERS -------------------------------
worker               listen                              processes status

解決方放

修改workerman下Worker.php檔案中的getStartFilesForWindows函式

public static function getStartFilesForWindows() {
        global $argv;
        $files = array();
        _$file = $argv;
        $files = $file;
        return $files;
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章