laravel+websocket是即时通讯开发必备利器,那么Laravel中怎么接入workerman?下面本篇文章给大家介绍一下laravel快速接入websocket的方法,希望对大家有所帮助。
前言:此处,我们采用基于workerman开发的GatewayWorker作为socket的核心组件,因为,workerman是一个纯粹的socket类库,相对于GatewayWorker来说,更底层,更需要开发者有多进程的编程经验,而我们大部分开发者使用workerman是为了做IM、或者游戏等,直接基于GatewayWorker开发,更快、更强。
composer require workerman/gateway-worker -vvv
通过下列命令,在App\Console\Commands下创建命令行文件,并将下方代码复制到文件中。【相关推荐:《workerman教程》】
php artisan make:command WorkermanCommand
<?php namespace App\Console\Commands; use GatewayWorker\BusinessWorker; use GatewayWorker\Gateway; use GatewayWorker\Register; use Illuminate\Console\Command; use Workerman\Worker; class WorkermanCommand extends Command { protected $signature = 'workman {action} {--d}'; //执行该命令的方式 protected $description = 'Start a Workerman server.'; public function handle() { global $argv; $action = $this->argument('action'); $argv[0] = 'wk'; $argv[1] = $action; $argv[2] = $this->option('d') ? '-d' : ''; // -d守护模式,不会因为关闭系统命令页面而被杀掉进程。 没有-d则关闭命令页面直接退出进程 $this->start(); } private function start() { $this->startGateWay(); $this->startBusinessWorker(); $this->startRegister(); Worker::runAll(); } private function startBusinessWorker() { $worker = new BusinessWorker(); $worker->name = 'BusinessWorker'; $worker->count = 1; $worker->registerAddress = '127.0.0.1:1236'; $worker->eventHandler = \App\Events::class; //用作监听事件的文件 } private function startGateWay() { //因为小程序等一些平台,要求使用wss进行socket,所以,这里需要配置下wss //此处的cert.pem和key.key是域名的证书文件 $content = array( 'ssl' => array( 'local_cert' => public_path('cert.pem'), 'local_pk' => public_path('key.key'), 'verify_peer' => false ) ); $gateway = new Gateway("websocket://0.0.0.0:2346", $content); //如果不需要wss,则不用加入content这个参数 $gateway->transport = 'ssl';//不需要wss,也不用加入这个参数。 $gateway->name = 'Gateway'; $gateway->count = 1; $gateway->lanIp = '127.0.0.1'; $gateway->startPort = 2300; $gateway->pingInterval = 30; $gateway->pingNotResponseLimit = 0; $data = array( 'type' => 'heart' ); $gateway->pingData = json_encode($data, true); $gateway->registerAddress = '127.0.0.1:1236'; } private function startRegister() { new Register('text://0.0.0.0:1236'); } }
创建一个app/Events.php文件来监听处理Workman的各种事件
<?php namespace App\Workerman; class Events { public static function onWorkerStart($businessWorker) { } public static function onConnect($client_id) { } public static function onWebSocketConnect($client_id, $data) { } public static function onMessage($client_id, $message) { } public static function onClose($client_id) { } }
在命令行里面执行,支持的命令有 start | stop | restart,后续加 -d 的意思是守护模式【daemon】
php artisan workman start -d
1、在LINUX环境中使用。
2、有可能会启动失败,此时,请检查php中,是否禁用了pcntl开头的相关方法。在 php配置文件中查找到disable_functions,将所有pcntl开头的方法全部删除。
更多编程相关知识,请访问:编程教学!!
以上是聊聊Laravel中怎么接入workerman的详细内容。更多信息请关注PHP中文网其他相关文章!