laravel 整合WorkerMan

我的开发环境是基于laravel官方推荐的homestead虚拟机

首先执行  composer require workerman/workerman  安装workerman

artisan command实现

因为workerman服务启动是基于cli命令行模式,所以我们得用laravel的artisan来实现.

创建command

php artisan make:command WorkermanHttpserver

注册command

App\Console\Kernel.php文件添加刚才创建的command

protected $commands = [

  Commands\WorkermanHttpServer::class

];

以下例子是创建一个简单的httpserver.其他服务请查看官方文档.

参考官方文档,在WorkermanHttpServer.php 中写如下内容:

  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Workerman\Worker;
  5. use App;
  6. class WorkermanHttpServer extends Command
  7. {
  8.  protected $httpserver;
  9.  /**
  10.  * The name and signature of the console command.
  11.  *
  12.  * @var string
  13.  */
  14.  protected $signature = 'workerman:httpserver {action} {--daemonize}';
  15.  /**
  16.  * The console command description.
  17.  *
  18.  * @var string
  19.  */
  20.  protected $description = 'workerman httpserver';
  21.  /**
  22.  * Create a new command instance.
  23.  *
  24.  * @return void
  25.  */
  26.  public function __construct()
  27.  {
  28.  parent::__construct();
  29.  }
  30.  /**
  31.  * Execute the console command.
  32.  *
  33.  * @return mixed
  34.  */
  35.  public function handle()
  36.  {
  37.  //因为workerman需要带参数 所以得强制修改
  38.  global $argv;
  39.  $action=$this->argument('action');
  40.  if(!in_array($action,['start','stop'])){
  41.  $this->error('Error Arguments');
  42.  exit;
  43.  }
  44.  $argv[0]='workerman:httpserver';
  45.  $argv[1]=$action;
  46.  $argv[2]=$this->option('daemonize')?'-d':'';
  47.  $this->httpserver=new Worker('http://0.0.0.0:8080');
  48.  // App::instance('workerman:httpserver',$this->httpserver);
  49.  $this->httpserver->onMessage=function($connection,$data){
  50.  $connection->send('laravel workerman hello world');
  51.  };
  52.  Worker::runAll();
  53.  }
  54. }

运行command 

php artisan workerman:httpserver start

php artisan workerman:httpserver start --daemonize //常驻后台运行

 

 

 

整合gatewayworker

 

1.安装 Gateway-worker

由于要使用客户端点对点通讯,选择了 workerman/gateway-worker 的扩展包,它已经引入了 workerman/workerman 。

$ composer require workerman/gateway-worker
 

2.创建 Workerman 启动文件

创建一个 artisan 命令行工具来启动 Socket 服务端,在 app/Console/Commands 目录下建立命令行文件。

<?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' : '';

        $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\Workerman\Events::class;
    }

    private function startGateWay()
    {
        $gateway = new Gateway("websocket://0.0.0.0:2346");
        $gateway->name                 = 'Gateway';
        $gateway->count                = 1;
        $gateway->lanIp                = '127.0.0.1';
        $gateway->startPort            = 2300;
        $gateway->pingInterval         = 30;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = '{"type":"@heart@"}';
        $gateway->registerAddress      = '127.0.0.1:1236';
    }

    private function startRegister()
    {
        new Register('text://0.0.0.0:1236');
    }
}
 

3.创建事件监听文件

创建一个 app/Workerman/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)
    {
    }
}
 

4.启动 Workerman 服务端

在命令行里面执行,支持的命令大概有 start|stop|restart,其中 -d 的意思是 daemon 模式。

$ php artisan workman start --d

当你看到如下结果的时候,workman已经启动成功了。

Workerman[wk] start in DEBUG mode
----------------------- WORKERMAN -----------------------------
Workerman version:3.5.11          PHP version:7.1.11
------------------------ WORKERS -------------------------------
user          worker          listen                    processes status
root          Gateway         websocket://0.0.0.0:2346   1         [OK]
root          BusinessWorker  none                       1         [OK]
root          Register        text://0.0.0.0:1236        1         [OK]
----------------------------------------------------------------
Press Ctrl+C to stop. Start success.
onWorkerStart

前端代码
<script>
ws = new WebSocket("ws://"+document.domain+":2346");
ws.onopen = function() {
console.log("连接成功");

var login_info = {
"event":"login",
"info":"{{auth()->id()??'游客'}}"
};
login_info = JSON.stringify(login_info);
ws.send(login_info);
console.log("{{auth()->user()?auth()->user()->name:'游客'}}" + "登录");
};
ws.onmessage = function(e) {
console.log(e);
};

function send() {
var info = {
"event":"say",
"info":"hello world!!!"
};
info = JSON.stringify(info);
ws.send(info);
}
</script>

服务器通过gateway-worker-cli 向客户端发送消息
\GatewayWorker\Lib\Gateway::$registerAddress = '127.0.0.1:1236';
\GatewayWorker\Lib\Gateway::sendToAll($word);
 

 

posted @ 2018-07-28 14:05  花泪哲  阅读(9887)  评论(1)    收藏  举报