Socket.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. class Socket extends Command
  5. {
  6. public $ws;
  7. /**
  8. * The name and signature of the console command.
  9. *
  10. * @var string
  11. */
  12. protected $signature = 'swoole:socket {op?}';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = 'websocket ';
  19. /**
  20. * Create a new command instance.
  21. *
  22. * @return void
  23. */
  24. public function __construct()
  25. {
  26. parent::__construct();
  27. }
  28. /**
  29. * Execute the console command.
  30. *
  31. * @return mixed
  32. */
  33. public function handle()
  34. {
  35. $op = $this->argument('op');
  36. $op = $op? $op : 'start';
  37. if($op == 'start'){
  38. echo 'socket start ...';
  39. $this->start();
  40. }else if ($op == 'stop'){
  41. echo 'socket stop ...';
  42. $this->stop();
  43. }
  44. }
  45. /**
  46. * 运行
  47. */
  48. public function start()
  49. {
  50. //创建websocket服务器对象,监听0.0.0.0:7104端口
  51. $this->ws = new \swoole_websocket_server("0.0.0.0", env('SOCKET_PORT','6420'));
  52. //监听WebSocket连接打开事件
  53. $this->ws->on('open',[$this,'open']);
  54. //监听WebSocket消息事件
  55. $this->ws->on('message',[$this,'message']);
  56. //监听WebSocket主动推送消息事件
  57. $this->ws->on('request',[$this,'request']);
  58. //监听WebSocket连接关闭事件
  59. $this->ws->on('close',[$this,'close']);
  60. $this->ws->start();
  61. }
  62. /**
  63. * 建立连接
  64. * @param $ws
  65. * @param $request
  66. */
  67. public function open($ws, $request){
  68. var_dump($request->fd . "连接成功");
  69. }
  70. /**
  71. * 接收消息
  72. * @param $ws
  73. * @param $frame
  74. */
  75. public function message($ws,$frame){
  76. $this->ws->push($frame->fd, '收到消息');
  77. }
  78. /**
  79. * 接收请求
  80. * @param $request
  81. * @param $response
  82. */
  83. public function request($request,$response){
  84. }
  85. /**
  86. * 关闭连接
  87. * @param $ws
  88. * @param $fd
  89. */
  90. public function close($ws,$fd){
  91. $this->ws->close();
  92. }
  93. /**
  94. * 停止运行
  95. */
  96. public function stop()
  97. {
  98. $this->ws->close();
  99. }
  100. }