Last active
January 7, 2016 04:16
-
-
Save cyonks/93d6c4c83b8cb5807064 to your computer and use it in GitHub Desktop.
基于swoole_server的简单Http服务器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//1.构建Server对象 | |
$serv = new swoole_server("0.0.0.0", 9501); | |
//2.设置运行时参数 | |
$serv->set(array( | |
'worker_num' => 8, | |
'daemonize' => 0, | |
'max_request' => 10000, | |
'dispatch_mode' => 2, | |
'debug_mode'=> 1, | |
)); | |
//3.注册事件回调函数 | |
$serv->on('Receive', function($serv, $fd, $from_id, $data){ | |
$respData='<h1>Hello Swoole.</h1>'; | |
response($serv,$fd,$respData);//封装并发送HTTP响应报文 | |
}); | |
//4.启动服务器 | |
$serv->start(); | |
/** | |
* 发送内容 | |
* @param \swoole_server $serv | |
* @param int $fd | |
* @param string $respData | |
* @return void | |
*/ | |
function response($serv,$fd,$respData){ | |
//响应行 | |
$response = array( | |
'HTTP/1.1 200', | |
); | |
//响应头 | |
$headers = array( | |
'Server'=>'SwooleServer', | |
'Content-Type'=>'text/html;charset=utf8', | |
'Content-Length'=>strlen($respData), | |
); | |
foreach($headers as $key=>$val){ | |
$response[] = $key.':'.$val; | |
} | |
//空行 | |
$response[] = ''; | |
//响应体 | |
$response[] = $respData; | |
$send_data = join("\r\n",$response); | |
$serv->send($fd, $send_data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment