版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39967349/article/details/86137060
ps:本次配置是在laravel5.4的基础上演示
1.首先安装workerman
composer require workerman/workerman
2.服务端启动
php artisan make:command Workerman
然后>/app/Console/Commands下面就会创建一个文件Workerman.php
我们改一改signature description 还有handle方法...↓
记得引入workerman
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Workerman\Worker; class Workerman extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'workerman:command {action} {-d}'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $ws = new Worker("websocket://0.0.0.0:9011"); $ws->count = 4; // $ws_connection = new Worker("websocket://0.0.0.0:9012"); // $ws_connection->count = 1; // $ws->onConnect = function($connection) // { // // }; $ws->onMessage = function($connection, $data) { echo $data."\n"; $connection->send($data); }; $ws->onClose = function($connection) { echo "Connection closed\n"; }; // 开启多少个进程运行定时任务,注意业务是否在多进程有并发问题 $ws->onWorkerStart = function($ws) { echo "Worker starting...\n"; // 以websocket协议连接远程websocket服务器 $ws->onConnect = function($connection){ // 每10秒执行一次 $time_interval = 1; // 给connection对象临时添加一个timer_id属性保存定时器id $connection->timer_id = Timer::add($time_interval, function()use($connection) { $connect_time = time(); $connection->send($connect_time); }); }; }; // Run worker Worker::runAll(); } }
3.修改/app/Console/Kernel.php
protected $commands = [ Commands\Workerman::class, ];
4.启动workerman
php artisan workerman:command start d