Http.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\worker;
  12. use RecursiveDirectoryIterator;
  13. use RecursiveIteratorIterator;
  14. use Workerman\Connection\TcpConnection;
  15. use Workerman\Lib\Timer;
  16. use Workerman\Protocols\Http as WorkerHttp;
  17. use Workerman\Worker;
  18. /**
  19. * Worker http server 命令行服务类
  20. */
  21. class Http extends Server
  22. {
  23. protected $app;
  24. protected $rootPath;
  25. protected $root;
  26. protected $appInit;
  27. protected $monitor;
  28. protected $lastMtime;
  29. /** @var array Mime mapping. */
  30. protected static $mimeTypeMap = [];
  31. /**
  32. * 架构函数
  33. * @access public
  34. * @param string $host 监听地址
  35. * @param int $port 监听端口
  36. * @param array $context 参数
  37. */
  38. public function __construct($host, $port, $context = [])
  39. {
  40. $this->worker = new Worker('http://' . $host . ':' . $port, $context);
  41. // 设置回调
  42. foreach ($this->event as $event) {
  43. if (method_exists($this, $event)) {
  44. $this->worker->$event = [$this, $event];
  45. }
  46. }
  47. }
  48. public function setRootPath($path)
  49. {
  50. $this->rootPath = $path;
  51. }
  52. public function appInit(\Closure $closure)
  53. {
  54. $this->appInit = $closure;
  55. }
  56. public function setRoot($path)
  57. {
  58. $this->root = $path;
  59. }
  60. public function setStaticOption($name, $value)
  61. {
  62. Worker::${$name} = $value;
  63. }
  64. public function setMonitor($interval = 2, $path = [])
  65. {
  66. $this->monitor['interval'] = $interval;
  67. $this->monitor['path'] = (array) $path;
  68. }
  69. /**
  70. * 设置参数
  71. * @access public
  72. * @param array $option 参数
  73. * @return void
  74. */
  75. public function option(array $option)
  76. {
  77. // 设置参数
  78. if (!empty($option)) {
  79. foreach ($option as $key => $val) {
  80. $this->worker->$key = $val;
  81. }
  82. }
  83. }
  84. /**
  85. * onWorkerStart 事件回调
  86. * @access public
  87. * @param \Workerman\Worker $worker
  88. * @return void
  89. */
  90. public function onWorkerStart($worker)
  91. {
  92. $this->initMimeTypeMap();
  93. $this->app = new Application($this->rootPath);
  94. if ($this->appInit) {
  95. call_user_func_array($this->appInit, [$this->app]);
  96. }
  97. $this->app->initialize();
  98. $this->lastMtime = time();
  99. $this->app->workerman = $worker;
  100. $this->app->bind([
  101. 'think\Cookie' => Cookie::class,
  102. ]);
  103. if (0 == $worker->id && $this->monitor) {
  104. $paths = $this->monitor['path'];
  105. $timer = $this->monitor['interval'] ?: 2;
  106. Timer::add($timer, function () use ($paths) {
  107. foreach ($paths as $path) {
  108. $dir = new RecursiveDirectoryIterator($path);
  109. $iterator = new RecursiveIteratorIterator($dir);
  110. foreach ($iterator as $file) {
  111. if (pathinfo($file, PATHINFO_EXTENSION) != 'php') {
  112. continue;
  113. }
  114. if ($this->lastMtime < $file->getMTime()) {
  115. echo '[update]' . $file . "\n";
  116. posix_kill(posix_getppid(), SIGUSR1);
  117. $this->lastMtime = $file->getMTime();
  118. return;
  119. }
  120. }
  121. }
  122. });
  123. }
  124. }
  125. /**
  126. * onMessage 事件回调
  127. * @access public
  128. * @param TcpConnection $connection
  129. * @param mixed $data
  130. * @return void
  131. */
  132. public function onMessage($connection, $data)
  133. {
  134. $uri = parse_url($_SERVER['REQUEST_URI']);
  135. $path = $uri['path'] ?? '/';
  136. $file = $this->root . $path;
  137. if (!is_file($file)) {
  138. $this->app->worker($connection, $data);
  139. } else {
  140. $this->sendFile($connection, $file);
  141. }
  142. }
  143. /**
  144. * 访问资源文件
  145. * @access protected
  146. * @param TcpConnection $connection
  147. * @param string $file 文件名
  148. * @return string
  149. */
  150. protected function sendFile($connection, $file)
  151. {
  152. $info = stat($file);
  153. $modifiyTime = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' ' . date_default_timezone_get() : '';
  154. if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info) {
  155. // Http 304.
  156. if ($modifiyTime === $_SERVER['HTTP_IF_MODIFIED_SINCE']) {
  157. // 304
  158. WorkerHttp::header('HTTP/1.1 304 Not Modified');
  159. // Send nothing but http headers..
  160. return $connection->close('');
  161. }
  162. }
  163. $mimeType = $this->getMimeType($file);
  164. WorkerHttp::header('HTTP/1.1 200 OK');
  165. WorkerHttp::header('Connection: keep-alive');
  166. if ($mimeType) {
  167. WorkerHttp::header('Content-Type: ' . $mimeType);
  168. } else {
  169. WorkerHttp::header('Content-Type: application/octet-stream');
  170. $fileinfo = pathinfo($file);
  171. $filename = $fileinfo['filename'] ?? '';
  172. WorkerHttp::header('Content-Disposition: attachment; filename="' . $filename . '"');
  173. }
  174. if ($modifiyTime) {
  175. WorkerHttp::header('Last-Modified: ' . $modifiyTime);
  176. }
  177. WorkerHttp::header('Content-Length: ' . filesize($file));
  178. ob_start();
  179. readfile($file);
  180. $content = ob_get_clean();
  181. return $connection->send($content);
  182. }
  183. /**
  184. * 获取文件类型信息
  185. * @access protected
  186. * @param string $filename 文件名
  187. * @return string
  188. */
  189. protected function getMimeType(string $filename)
  190. {
  191. $file_info = pathinfo($filename);
  192. $extension = $file_info['extension'] ?? '';
  193. if (isset(self::$mimeTypeMap[$extension])) {
  194. $mime = self::$mimeTypeMap[$extension];
  195. } else {
  196. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  197. $mime = finfo_file($finfo, $filename);
  198. }
  199. return $mime;
  200. }
  201. /**
  202. * Init mime map.
  203. *
  204. * @return void
  205. * @throws \Exception
  206. */
  207. protected function initMimeTypeMap()
  208. {
  209. $mime_file = WorkerHttp::getMimeTypesFile();
  210. if (!is_file($mime_file)) {
  211. Worker::log("$mime_file mime.type file not fond");
  212. return;
  213. }
  214. $items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  215. if (!is_array($items)) {
  216. Worker::log("get $mime_file mime.type content fail");
  217. return;
  218. }
  219. foreach ($items as $content) {
  220. if (preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match)) {
  221. $mime_type = $match[1];
  222. $workerman_file_extension_var = $match[2];
  223. $workerman_file_extension_array = explode(' ', substr($workerman_file_extension_var, 0, -1));
  224. foreach ($workerman_file_extension_array as $workerman_file_extension) {
  225. self::$mimeTypeMap[$workerman_file_extension] = $mime_type;
  226. }
  227. }
  228. }
  229. }
  230. /**
  231. * 启动
  232. * @access public
  233. * @return void
  234. */
  235. public function start()
  236. {
  237. Worker::runAll();
  238. }
  239. /**
  240. * 停止
  241. * @access public
  242. * @return void
  243. */
  244. public function stop()
  245. {
  246. Worker::stopAll();
  247. }
  248. }