1. 創建自定義 artisan 命令 php artisan make:command SwooleManger // 默認在 app/Console/Commans 目錄下創建 SwooleManger.php 文件。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
class SwooleManger extends Command
{
private $server;
private $pid_file;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature='swoole {action}';
/**
* The console command description.
*
* @var string
*/
protected $description='start or stop the swoole process';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->pid_file=__DIR__.'/../../../storage/swoole_websocket.pid';
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//獲取傳遞的操作
$arg=$this->argument('action');
switch ($arg){
case 'start':
//檢測進程是否已開啟
$pid=$this->getPid();
if($pid && \Swoole\Process::kill($pid,0))
{
$this->error("\r\nprocess already exist!\r\n");
exit;
}
$this->server=new \swoole_websocket_server("0.0.0.0", 9501);
$this->server->set([
'worker_num'=>8,
'daemonize'=>1,
'max_request'=>1000,
'dispatch_mode'=>2,
'pid_file'=>$this->pid_file,
]);
//綁定操作類回調函數
$app=App::make('App\Handles\SwooleWebSocketHandle');
$this->server->on('open',array($app,'onOpen'));
$this->server->on('message',array($app,'onMessage'));
$this->server->on('close',array($app,'onClose'));
$this->info("\r\nprocess created successful!\r\n");
$this->server->start();
break;
case 'stop':
if(!$pid=$this->getPid())
{
$this->error("\r\nprocess not started!\r\n");
exit;
}
if(\Swoole\Process::kill((int)$pid))
{
$this->info("\r\nprocess close successful!\r\n");
exit;
}
$this->info("\r\nprocess close failed!\r\n");
break;
default:
$this->error("\r\noperation method does not exist!\r\n");
}
}
//獲取pid
private function getPid()
{
return file_exists($this->pid_file) ? file_get_contents($this->pid_file) :false;
}
}
以上命令定義完成可使用 artisan 來管理 swoole websocket 服務的開啟和關閉
php artisan swoole start //開啟
php artisan swoole stop //關閉
2. 使用 Handles 類來處理 swoole 的事件處理
//在SwooleManger中使用了
$app=App::make('App\Handles\SwooleWebSocketHandle'); //將SwooleWebsocketHandle注入到SwooleManger中
使用 $this->server->on 注冊事件回調函數,創建 App\Handles\SwooleWebSocketHandle 文件實現 webSocket 的事件即可
原文鏈接Laravel 5.6 中優雅的管理 swoole 進程。
希望以上內容能幫助到大家,獲取更多的swoole學習資料以及視頻源碼筆記。
Swoole 在 1.x - 4.x 版本中同時提供了 PSR-0 規范的下劃線風格類名和 PSR-4 的命名空間風格。目前 PSR-0 規范已于2014年10月21日被標記為棄用,目前最新的替代規范為 PSR-4。
根據報道,在最新的 Swoole 5 版本中計劃將徹底移除下劃線類名,并且希望 Swoole 的用戶能逐步將類名改為 PSR-4 規范的純命名空間風格。
現在 Swoole 正在逐漸重構,移除陳舊落后的設計,未來會變得越來越精致。
正確使用
$server=new Swoole\Http\Server; $server=new Swoole\Server; $client=new Swoole\Coroutine\Http\Client; $client=new Co\Http\Client;
錯誤使用
$server=new Swoole_Http_Server; $server=new Swoole_Server; $client=new Swoole_Coroutine_Http_Client; $client=new Co_Http_Client;
當在 5.0 版本中將不再支持下劃線類名時,使用了上述風格代碼的 PHP 就會報類不存在的致命錯誤。
消息來源 https://segmentfault.com/a/1190000019532276
閱讀原文:「鏈接」