transfer1b.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. define('CONFIG_FILE', __DIR__ . '/config.php');
  3. define('LOG_NAME', 'transfer1b');
  4. define('DGRAM_MAXSIZE', 1000); //理论上限65507,内网建议值1472,公网建议值548
  5. include __DIR__ . '/functions.php';
  6. include __DIR__ . '/class.async.php';
  7. //加载配置
  8. $cfg = [];
  9. load_config();
  10. //检查参数
  11. $addr = "{$cfg['udp_host']}:{$cfg['udp_port']}";
  12. $quit = $restart = false;
  13. //保障只运行一个进程
  14. $lockFile = run_single_instance($cfg['udp_port']);
  15. //设置信号处理函数
  16. pcntl_signal(SIGTERM, 'sig_handle', false);
  17. pcntl_signal(SIGUSR1, 'sig_handle', false);
  18. pcntl_signal(SIGUSR2, 'sig_handle', false);
  19. //创建UDP服务
  20. $s = stream_socket_server("udp://{$addr}", $errno, $error, STREAM_SERVER_BIND);
  21. if (!$s) {
  22. debug_log("Transfer@{$addr} stream_socket_server() call failed: #{$errno},{$error}", 'ERROR', LOG_NAME);
  23. exit(1);
  24. }
  25. //接收UDP请求
  26. try {
  27. $async = new Async($cfg['redis_host'], $cfg['redis_port'], $cfg['worker_num']);
  28. debug_log("Transfer@{$addr} started, pid = " . getmypid(), 'DEBUG', LOG_NAME);
  29. while (1) {
  30. $buffer = '';
  31. declare (ticks = 1) {
  32. $buffer = stream_socket_recvfrom($s, DGRAM_MAXSIZE, 0, $from);
  33. }
  34. if (empty($buffer)) {
  35. if ($quit) { //退出
  36. debug_log("Transfer@{$addr} quiting", 'WARNING', LOG_NAME);
  37. fclose($s);
  38. unlink($lockFile);
  39. exit(0);
  40. } elseif ($restart) { //重启
  41. fclose($s);
  42. unlink($lockFile);
  43. debug_log("Transfer@{$addr} restarting", 'WARNING', LOG_NAME);
  44. pcntl_exec($cfg['php_bin_path'], $argv);
  45. debug_log("Transfer@{$addr} restart failed", 'ERROR', LOG_NAME);
  46. exit(1);
  47. } else { //定时器
  48. $async->ping();
  49. }
  50. } else {
  51. $data = json_decode($buffer, true);
  52. if (!empty($data) && is_array($data)) {
  53. $async->pushJob($data);
  54. }
  55. }
  56. }
  57. } catch (RedisException $e) {
  58. debug_log("Transfer@{$addr} catched an RedisException:" . $e->getMessage(), 'EXCEPTION', LOG_NAME);
  59. }
  60. fclose($s);
  61. unlink($lockFile);
  62. /**
  63. * 信号处理函数
  64. * @param int $signo 信号
  65. */
  66. function sig_handle($signo)
  67. {
  68. global $quit, $restart;
  69. switch ($signo)
  70. {
  71. //退出
  72. case SIGTERM:
  73. $quit = true;
  74. break;
  75. //重启
  76. case SIGUSR1:
  77. $restart = true;
  78. break;
  79. //定时器
  80. case SIGUSR2:
  81. break;
  82. }
  83. }