SwooleWorkerStart.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 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 app\common\repositories\store\service\StoreServiceUserRepository;
  13. use crmeb\interfaces\ListenerInterface;
  14. use Swoole\Server;
  15. use Swoole\Timer;
  16. use think\Config;
  17. use think\facade\Cache;
  18. /**
  19. * Class SwooleWorkerStart
  20. * @package app\webscoket
  21. * @author xaboy
  22. * @day 2020-04-29
  23. */
  24. class SwooleWorkerStart implements ListenerInterface
  25. {
  26. /**
  27. * @var \Swoole\WebSocket\Server
  28. */
  29. protected $server;
  30. /**
  31. * @var Config
  32. */
  33. protected $config;
  34. /**
  35. * SwooleWorkerStart constructor.
  36. * @param Server $server
  37. * @param Config $config
  38. */
  39. public function __construct(Server $server, Config $config)
  40. {
  41. $this->server = $server;
  42. $this->config = $config;
  43. }
  44. /**
  45. * @param $event
  46. * @author xaboy
  47. * @day 2020-04-29
  48. */
  49. public function handle($event): void
  50. {
  51. if (!env('INSTALLED', false)) return;
  52. if ($this->server->worker_id == ($this->config->get('swoole.server.options.worker_num')) && $this->config->get('swoole.websocket.enable', false)) {
  53. $keys = array_merge(Cache::keys('m_chat*'), Cache::keys('u_chat*'));
  54. if (count($keys)) {
  55. Cache::del(...$keys);
  56. }
  57. $this->ping();
  58. app()->make(StoreServiceUserRepository::class)->onlineDown();
  59. }
  60. }
  61. /**
  62. * @author xaboy
  63. * @day 2020-05-06
  64. */
  65. protected function ping()
  66. {
  67. /**
  68. * @var $pingService Ping
  69. */
  70. $pingService = app()->make(Ping::class);
  71. $server = $this->server;
  72. $timeout = (int)($this->config->get('swoole.websocket.ping_timeout', 60000) / 1000);
  73. Timer::tick(1500, function (int $timer_id) use (&$server, &$pingService, $timeout) {
  74. $nowTime = time();
  75. foreach ($server->connections as $fd) {
  76. if ($server->isEstablished($fd) && $server->exist($fd)) {
  77. $last = $pingService->getLastTime($fd);
  78. if ($last && ($nowTime - $last) > $timeout) {
  79. $server->close($fd);
  80. }
  81. }
  82. }
  83. });
  84. }
  85. }