如何用如何用PHP来实现一个动态来实现一个动态Web服务器服务器
要是现实一个 web 服务器,那么就需要大概了解 web 服务器的运行原理。先从静态的文本服务器开始,以访问 web 服务器
的1.html为例
1.客户端通过发送一个 http 请求到服务器,如果服务器监听的端口号是9002,那么在本机自身测试访问的地址就是
http://localhost:9002/1.html。
2.服务器监听着9002端口,那么在收到请求了请求之后,就能从 http head 头中获取到请求里需要访问的 uri 资源在web 目录
中的位置。
3.服务器读取需要访问的资源文件,然后填充到 http 的实体中返回给客户端。
示意图如下:
<?php
class web_config {
// 监听的端口号
const PORT = 9003;
// 项目根目录
const WEB_ROOT = "/Users/zhoumengkang/Documents/html";
}
class server {
private $ip;
private $port;
public function __construct($ip, $port) {
$this->ip = $ip;
$this->port = $port;
$this->await();
}
private function await() {
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($sock < 0) {
echo "Error:" . socket_strerror(socket_last_error()) . "\n";
}
$ret = socket_bind($sock, $this->ip, $this->port);
if (!$ret) {
echo "BIND FAILED:" . socket_strerror(socket_last_error()) . "";
exit;
}
echo "OK";
$ret = socket_listen($sock);
if ($ret < 0) {
echo "LISTEN FAILED:" . socket_strerror(socket_last_error()) . "";
}
do {
$new_sock = null;
try {
$new_sock = socket_accept($sock);
} catch (Exception $e) {
echo $e->getMessage();
echo "ACCEPT FAILED:" . socket_strerror(socket_last_error()) . "";
}
try {
$request_string = socket_read($new_sock, 1024);
$response = $this->output($request_string);
socket_write($new_sock, $response);
socket_close($new_sock);
} catch (Exception $e) {
echo $e->getMessage();
echo "READ FAILED:" . socket_strerror(socket_last_error()) . "";
}
} while (TRUE);
}
/**
* @param $request_string