| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- class Socket extends Command
- {
- public $ws;
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'swoole:socket {op?}';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'websocket ';
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
- {
- parent::__construct();
- }
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- public function handle()
- {
- $op = $this->argument('op');
- $op = $op? $op : 'start';
- if($op == 'start'){
- echo 'socket start ...';
- $this->start();
- }else if ($op == 'stop'){
- echo 'socket stop ...';
- $this->stop();
- }
- }
- /**
- * 运行
- */
- public function start()
- {
- //创建websocket服务器对象,监听0.0.0.0:7104端口
- $this->ws = new \swoole_websocket_server("0.0.0.0", env('SOCKET_PORT','6420'));
- //监听WebSocket连接打开事件
- $this->ws->on('open',[$this,'open']);
- //监听WebSocket消息事件
- $this->ws->on('message',[$this,'message']);
- //监听WebSocket主动推送消息事件
- $this->ws->on('request',[$this,'request']);
- //监听WebSocket连接关闭事件
- $this->ws->on('close',[$this,'close']);
- $this->ws->start();
- }
- /**
- * 建立连接
- * @param $ws
- * @param $request
- */
- public function open($ws, $request){
- var_dump($request->fd . "连接成功");
- }
- /**
- * 接收消息
- * @param $ws
- * @param $frame
- */
- public function message($ws,$frame){
- $this->ws->push($frame->fd, '收到消息');
- }
- /**
- * 接收请求
- * @param $request
- * @param $response
- */
- public function request($request,$response){
- }
- /**
- * 关闭连接
- * @param $ws
- * @param $fd
- */
- public function close($ws,$fd){
- $this->ws->close();
- }
- /**
- * 停止运行
- */
- public function stop()
- {
- $this->ws->close();
- }
- }
|