nginx-2 处理http请求

nginx服务器可以接收http请求并且响应http,如果用socket来模拟大概是这样:

建立一个tcp服务器
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
绑定端口号
socket_bind($socket, '0.0.0.0', 6001);
监听端口
socket_listen($socket, 5);
让服务永不退出
while(true){
	建立的客户端连接
	$client = socket_accept($server);
	读取客户端信号
    $buf = socket_read($client, 1024);
    处理信号
    // 响应$response内容...*处理信号的逻辑在这里*...
    向客户端写入信号
    socket_write($client,$response);
    socket_close($client);
}
关闭tcp服务器
socket_close($server);

读取客户端(浏览器)信号$buf
上边读取到客户端的信号buf,如果我请求的地址是这样:
在这里插入图片描述
那么打印buf:

在这里插入图片描述
buf是一长串字符串,用正则来匹配该字符串:

$preg = '#GET (.*) HTTP/1.1#iU';
preg_match($preg, $buf, $arr);
$request = $arr[1];

匹配的(.*)是:
在这里插入图片描述
这样我们就拿到了请求的内容。

响应$response
显示到页面上,响应字符串中需包含一些信息。

$content = 'your request is  '.$request; //your request is /index
$response="HTTP/1.1 200 OK\r\n";
$response.="Content-Type: text/html;charset=utf-8\r\n";
$response.="Content-Length: ".strlen($content)."\r\n\r\n";
$response.=$content;

如果是加载静态页面或者php页面:
html页面
在这里插入图片描述
request:
在这里插入图片描述

$filePath = __DIR__ . '/html' . $path;
$content = file_get_contents($filePath);

php文件:
在这里插入图片描述
request:
在这里插入图片描述

$filePath = __DIR__ . '/php' . $path;
ob_start();
include $filePath;
$content = ob_get_contents();
ob_clean();

猜你喜欢

转载自blog.csdn.net/yt_php/article/details/87442045