SwooleWorkerStart.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\webscoket;
  12. use crmeb\interfaces\ListenerInterface;
  13. use Swoole\Server;
  14. use Swoole\Timer;
  15. use think\Config;
  16. /**
  17. * Class SwooleWorkerStart
  18. * @package app\webscoket
  19. * @author xaboy
  20. * @day 2020-04-29
  21. */
  22. class SwooleWorkerStart implements ListenerInterface
  23. {
  24. /**
  25. * @var \Swoole\WebSocket\Server
  26. */
  27. protected $server;
  28. /**
  29. * @var Config
  30. */
  31. protected $config;
  32. /**
  33. * SwooleWorkerStart constructor.
  34. * @param Server $server
  35. * @param Config $config
  36. */
  37. public function __construct(Server $server, Config $config)
  38. {
  39. $this->server = $server;
  40. $this->config = $config;
  41. }
  42. /**
  43. * @param $event
  44. * @author xaboy
  45. * @day 2020-04-29
  46. */
  47. public function handle($event): void
  48. {
  49. if (!env('INSTALLED', false)) return;
  50. if ($this->server->worker_id == ($this->config->get('swoole.server.options.worker_num')) && $this->config->get('swoole.websocket.enable', false)) {
  51. $this->ping();
  52. }
  53. }
  54. /**
  55. * @author xaboy
  56. * @day 2020-05-06
  57. */
  58. protected function ping()
  59. {
  60. /**
  61. * @var $pingService Ping
  62. */
  63. $pingService = app()->make(Ping::class);
  64. $server = $this->server;
  65. $timeout = (int)($this->config->get('swoole.websocket.ping_timeout', 60000) / 1000);
  66. Timer::tick(1500, function (int $timer_id) use (&$server, &$pingService, $timeout) {
  67. $nowTime = time();
  68. foreach ($server->connections as $fd) {
  69. if ($server->isEstablished($fd) && $server->exist($fd)) {
  70. $last = $pingService->getLastTime($fd);
  71. if ($last && ($nowTime - $last) > $timeout) {
  72. $server->close($fd);
  73. }
  74. }
  75. }
  76. });
  77. }
  78. }