public function __construct($opt, $config = 'default') { $this->webPath = $opt['path']; if (!empty($opt['config'])) { $this->configPath = $opt['config']; } $ip = empty($opt['ip']) ? '0.0.0.0' : $opt['ip']; $port = empty($opt['port']) ? '9501' : $opt['port']; $http = new swoole_websocket_server($ip, $port); if (isset($opt['d'])) { $daemonize = 1; } else { $daemonize = 0; } $worker_num = empty($opt['worker']) ? 4 : $opt['worker']; $http->set(array('worker_num' => $worker_num, 'daemonize' => $daemonize, 'max_request' => 0)); $http->setGlobal(HTTP_GLOBAL_ALL, HTTP_GLOBAL_GET | HTTP_GLOBAL_POST); $http->on('WorkerStart', array($this, 'onWorkerStart')); $http->on('WorkerError', array($this, 'onWorkerError')); $http->on('WorkerStop', array($this, 'onWorkerStop')); $http->on('close', function () { $params = func_get_args(); $conn = $params[0]->connection_info($params[1]); if ($conn['websocket_status'] > 1) { $parse = ZFactory::getInstance(ZConfig::getField('socket', 'parse_class', 'WebSocketChatParse')); $parse->close($this->zphp, $params[1]); } }); $http->on('open', function ($response) { $parse = ZFactory::getInstance(ZConfig::getField('socket', 'parse_class', 'WebSocketChatParse')); $parse->open($this->zphp, $response->fd); }); $http->on('message', function ($server, $frame) { HttpServer::$wsfarme = $frame; $parse = ZFactory::getInstance(ZConfig::getField('websocket', 'parse_class', 'WebSocketChatParse')); $parse->message($this->zphp, $frame); }); $http->on('request', function ($request, $response) { HttpServer::$request = $request; HttpServer::$response = $response; $_SERVER['PATH_INFO'] = $request->server['path_info']; if ($_SERVER['PATH_INFO'] == '/') { if (!empty($this->defaultFiles)) { foreach ($this->defaultFiles as $file) { $staticFile = $this->getStaticFile(DIRECTORY_SEPARATOR . $file); if (is_file($staticFile)) { $response->end(file_get_contents($staticFile)); return; } } } } if ($_SERVER['PATH_INFO'] == '/favicon.ico') { $response->header('Content-Type', $this->mimes['ico']); $response->end(''); return; } $staticFile = $this->getStaticFile($_SERVER['PATH_INFO']); if (\is_dir($staticFile)) { //是目录 foreach ($this->defaultFiles as $file) { if (is_file($staticFile . $file)) { $response->header('Content-Type', 'text/html'); $response->end(file_get_contents($staticFile . $file)); return; } } } $ext = \pathinfo($_SERVER['PATH_INFO'], PATHINFO_EXTENSION); if (isset($this->mimes[$ext])) { //非法的扩展名 if (\is_file($staticFile)) { //读取静态文件 $response->header('Content-Type', $this->mimes[$ext]); $response->end(file_get_contents($staticFile)); return; } else { $response->status(404); $response->end(''); return; } } try { ob_start(); $result = $this->zphp->run(); if (null == $result) { $result = ob_get_contents(); } ob_end_clean(); } catch (Exception $e) { $result = json_encode($e->getTrace()); } $response->status(200); $response->end($result); }); self::$http = $http; self::$http->start(); }