<?php namespace App\Console\Commands; use App\Http\Controllers\Auth\SwooleCommandController; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; class swoole extends Command { public $ws; private $token = 'zxc123456789ZXC'; public $time = 10; /** * The name and signature of the console command. * * @var string */ protected $signature = 'swoole {action?}'; /** * The console command description. * * @var string */ protected $description = 'swoole'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $action = $this->argument('action'); switch ($action) { case 'close': break; default: $this->start(); break; } } //开启WebSocket public function start() { $url = config('public.swoolwebsocketurl'); $por = config('public.swoolwebsocketurlpor'); $this->ws = new \swoole_websocket_server('0.0.0.0', 9502); //创建一个端口 $this->ws->set(array( 'reactor_num' => 2, //reactor线程数 'worker_num' => 4, //worker进程数 'backlog' => 128, //Listen队列长度 'max_request' => 10,//最大连接 'daemonize'=>0,//守护进程 )); $this->ws->on('open', function ($ws, $request) { // //链接成功 // $data = [ // 'code' => 200, // 'token' => md5($this->token), // 'time' => date("Y-m-d H:i:s", time()), // 'msg' => '连接成功' // ]; // $this->ws->push(1, json_encode($data), 1); $userdata = new SwooleCommandController(); $this->ws->push($request->fd,$userdata->userslist(),1); swoole_timer_tick(6000, function($timerId) use ($ws, $request) { $userdata = new SwooleCommandController(); $this->ws->push($request->fd,$userdata->userslist(),1); }); }); //监听WebSocket消息事件 $this->ws->on('message', function ($ws, $frame) { // $data = json_decode($frame->data, true); // //监测是否是有效链接 // if($this->ws->isEstablished($frame->fd)){ // $ws->bind($frame->fd, $data['id']); // $userdata = new SwooleCommandController(); // $this->ws->push($frame->fd,$userdata->userslist(),1); // }else{ // Log::channel('single')->info('不是有效连接'. ','.'id=>'. $frame->fd); // $this->ws->push($frame->fd, '不是有效连接', 1); // $this->ws->disconnect($frame->fd, 105, '已断开连接,不是有效连接'); // } //// $token = (string)$data['token']; //// if ($token != md5($this->token)) { //// Log::channel('single')->info('token错误'. ',' .'token=>'. $token . ',' . 'id=>' . $frame->fd); //// $this->ws->push($frame->fd, 'token错误', 1); //// $this->ws->disconnect($frame->fd, 105, '已断开连接,token错误'); //// } else { ////// //// } }); $this->ws->on('request', function ($request, $response) { if ($request->post['token'] == "123") { echo "123213"; $clients = $this->ws->getClientList(); } }); //监听WebSocket连接关闭事件 $this->ws->on('close', function ($ws, $fd) { echo "client:{$fd} is closed\n"; swoole_timer_clear($this->time); }); $this->ws->start(); } }