Laravel框架中集成并使用workerman、websocket流程步骤
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
看看效果区分linux、windows
linux:
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.
windows:
注意:
如果出现无法监听的情况
需要修改 workerman 下 Worker.php 文件中的 getStartFilesForWindows 函数
代码:
public static function getStartFilesForWindows() {
global $argv;
$files = array();
_$file = $argv;
$files = $file;
return $files;
}
完
相关文章