/** * 启动服务 */ function run() { $this->server = new \swoole_server($this->host, $this->port, $this->config['mode'], $this->config['sock_type']); $this->server->set($this->config['swoole_setting']); swoole_server_handler($this->server, 'onConnect', array($this, 'onConnect')); swoole_server_handler($this->server, 'onReceive', array($this, 'onReceive')); swoole_server_handler($this->server, 'onClose', array($this, 'onClose')); $this->server->start(); }
function run($setting = array()) { $set = array_merge($this->swooleSetting, $setting); swoole_server_set($this->sw, $set); swoole_server_handler($this->sw, 'onWorkerStart', array($this->protocol, 'onStart')); swoole_server_handler($this->sw, 'onConnect', array($this->protocol, 'onConnect')); swoole_server_handler($this->sw, 'onReceive', array($this->protocol, 'onReceive')); swoole_server_handler($this->sw, 'onClose', array($this->protocol, 'onClose')); swoole_server_handler($this->sw, 'onWorkerStop', array($this->protocol, 'onShutdown')); // swoole_server_handler($this->sw, 'onTimer', array($this->protocol, 'onReceive')); swoole_server_start($this->sw); }
function my_onReceive($serv, $fd, $from_id, $data) { //file_put_contents('/tmp/log', getmypid() . "\t" . memory_get_usage() . "\t" . memory_get_usage(true) . "\n", FILE_APPEND); //$request = http_parse($data); $data = "it work!"; $data = http_package($data); swoole_server_send($serv, $fd, $data); swoole_server_close($serv, $fd, $from_id); } function http_package($data) { $httpStr = "HTTP/1.1 200 OK\r\nServer: Swoole/1.5.4\r\nConnection: Close\r\n\r\n" . $data; return $httpStr; } function http_parse($data) { $tmp = explode("\r\n", $data); list($method, $uri, $version) = explode(' ', $tmp[0]); return array('method' => $method, 'uri' => $uri, 'version' => $version); } swoole_server_handler($serv, 'onStart', 'my_onStart'); swoole_server_handler($serv, 'onConnect', 'my_onConnect'); swoole_server_handler($serv, 'onReceive', 'my_onReceive'); swoole_server_handler($serv, 'onClose', 'my_onClose'); swoole_server_handler($serv, 'onShutdown', 'my_onShutdown'); swoole_server_handler($serv, 'onTimer', 'my_onTimer'); swoole_server_handler($serv, 'onWorkerStart', 'my_onWorkerStart'); swoole_server_handler($serv, 'onWorkerStop', 'my_onWorkerStop'); #swoole_server_addtimer($serv, 2); #swoole_server_addtimer($serv, 10); swoole_server_start($serv);