public function onWorkerStart($serv, $worker_id) { echo "Worker {$worker_id} start\n"; // TODO 在这里加载可能的全局变量 if (!$serv->taskworker) { SwooleServer::$PDO = new PDO("mysql:host=localhost;port=3306;dbname=Test", "root", "123456", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8';", PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true)); echo "Worker\n"; } }
/** * 记载配置文件 */ public function loadConf() { $iniPath = self::$_path . '/conf/serv_conf.ini'; $config = parse_ini_file($iniPath, true); // server log $config['SETTING']['log_file'] = self::$_path . '/log/swoole.log'; self::$_settings = array_merge(self::$_settings, $config['SETTING']); self::$_serverType = $config['LISTENING']['type']; self::$_serverPort = $config['LISTENING']['port']; self::$_name = $config['INFO']['name']; self::$businessSetting = $config['BUSINESS']; self::$bootFile = $config['bootFile']; }
function server_loop() { while (true) { $read_fds = $this->fds; if (stream_select($read_fds, $write = null, $exp = null, null)) { foreach ($read_fds as $socket) { $socket_id = (int) $socket; if ($socket_id == $this->server_socket_id) { if ($client_socket_id = parent::accept()) { $this->fds[$client_socket_id] = $this->client_sock[$client_socket_id]; $this->protocol->onConnect($client_socket_id); } } else { $data = sw_fread_stream($socket, $this->buffer_size); if ($data !== false) { $this->protocol->onRecive($socket_id, $data); } else { $this->close($socket_id); } } } } } }
function __construct($host, $port, $timeout = 30) { parent::__construct($host, $port, $timeout); }
<?php // 入口文件所在目录 define('ROOT_PATH', dirname(__FILE__)); require ROOT_PATH . '/lib/SwooleServer.php'; $a = SwooleServer::getInstance(ROOT_PATH); $a->run();