# Server ### 构建Server对象 ~~~ $serv = new swoole_server("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP); ~~~ > swoole_server只能用于php-cli环境 ### 设置运行时参数 ~~~ $serv->set(array('worker_num' => 4, 'daemonize' => true)); ~~~ ### 注册事件回调函数 ~~~ $serv->on('Connect', 'my_onConnect'); $serv->on('Receive', 'my_onReceive'); $serv->on('Close', 'my_onClose'); ~~~ ### 属性列表 ~~~ $serv->manager_pid; //管理进程的PID,通过向管理进程发送SIGUSR1信号可实现柔性重启 $serv->master_pid; //主进程的PID,通过向主进程发送SIGTERM信号可安全关闭服务器 ~~~ ### 运行流程图 ![Swoole扩展架构图](https://box.kancloud.cn/2016-08-30_57c5268f86e00.jpg) ### 进程/线程结构图 ![Swoole进程/线程结构图](https://box.kancloud.cn/2016-08-30_57c5268fb3216.jpg) ### 注意事项 - 不要在代码中执行sleep,这样会导致整个进程阻塞 - exit/die是危险的,会导致worker进程退出 - 可通过register_shutdown_function来捕获致命错误,在进程异常退出时做一些请求工作,具体如下 ~~~ register_shutdown_function('handleFatal'); function handleFatal() { $error = error_get_last(); if (isset($error['type'])) { switch ($error['type']) { case E_ERROR : case E_PARSE : case E_DEPRECATED: case E_CORE_ERROR : case E_COMPILE_ERROR : $message = $error['message']; $file = $error['file']; $line = $error['line']; $log = "$message ($file:$line)\nStack trace:\n"; $trace = debug_backtrace(); foreach ($trace as $i => $t) { if (!isset($t['file'])) { $t['file'] = 'unknown'; } if (!isset($t['line'])) { $t['line'] = 0; } if (!isset($t['function'])) { $t['function'] = 'unknown'; } $log .= "#$i {$t['file']}({$t['line']}): "; if (isset($t['object']) && is_object($t['object'])) { $log .= get_class($t['object']) . '->'; } $log .= "{$t['function']}()\n"; } if (isset($_SERVER['REQUEST_URI'])) { $log .= '[QUERY] ' . $_SERVER['REQUEST_URI']; } error_log($log); $serv->send($this->currentFd, $log); } } } ~~~