最近在做一个web缓存系统,作为一个web缓存系统,肯定得有一个web服务器的功能,即实现简单的http协议。于是,干脆自己动手写一个php的web server。(注明:本文的源码,可以在本人的资源分享里面下载)
在此之前,先介绍一下简单http协议。
协议包含两个重要内容。
Request格式:
HTTP请求行
(请求)头
空行
可选的消息体
典型例子:
GET /index.php HTTP/1.1 /r/n
Host: 192.168.2.166 /r/n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 /r/n
Accept-Language: en-us,en;q=0.5 /r/n
Accept-Encoding: gzip,deflate /r/n
Keep-Alive: 300 /r/n
Connection: keep-alive /r/n
HTTP响应格式:
(应答)头
空行
可选的消息体
HTTP/1.1 200 OK /r/n
Cache-Control: private, max-age=30 /r/n
Content-Type: text/html; charset=utf-8 /r/n
Content-Encoding: gzip /r/n
Expires: Mon, 25 May 2009 03:20:33 GMT /r/n
Last-Modified: Mon, 25 May 2009 03:20:03 GMT /r/n
Server: Microsoft-IIS/7.0 /r/n
Date: Mon, 25 May 2009 03:20:02 GMT /r/n
Content-Length: 5 /r/n
/r/n
hello //这里是消息的真正内容
本文只是简单介绍一下http请求头和响应头,具体的协议格式,请另行google。
Request是浏览器给我们的服务器发送的,也就是说,我们的服务器解析reques包,然后给予响应,就完成了一个简单的http协议通信过程。当然,在处理请求之前,得简历socket链接。(别说socket不会建立啊)。
下面直接从接收客户端请求开始。当浏览器跟服务器的80端口建立连接后,会发送request包。包格式前面介绍过。
接收到req包后,就是处理了。主要有三步,不管什么请求,先获取请求的类型。比 如浏览器访问这个链接:http://192.168.2.166/a.php?a=10&b=10,请求头第一行就是GET /a.php?a=10&b=10 HTTP/1.1 /r/n
拿到这个请求报文后,先解析出请求的类型,比如php类型的请求,png类型的,gif类型的等等类型的请求。例子中是php类型的请求。
然后获取请求对象文件:a.php。最后获取请求的参数:a=10 b=10
接下来,开始着手填充http响应头:
然后根据不同的类型,处理流程不一样。如果是php请求,则调用系统调用system("php-cgi a.php a=10 b=10")(如果没有装php-cgi,ubuntu下面用apt-get install php5-cgi安装)。如果不是php请求,则可以把所有的请求当成普通文件请求,即把文件的内容直接放到消息体里面。
其中,dealPHPMes函数就是处理php-cgi的响应。php-cgi的响应也是一个标准的http响应,有头有内容。通过查找/r/n/r/n就可以找到头和内容的分界。
如果浏览器请求的是普通的请求,即非php请求,比如png请求,css请求,对于这些请求,只要把这些文件发送给浏览器即可。
最后调用socket的send函数,把上面的buf里面的内容全部发送给浏览器,浏览器就可以正常显示了。
到这里,一个简单的php web server已经实现。
另外提供源码下载地址:http://d.download.csdn.net/down/3288415/semillon
已经实现的功能有:
1.php支持
2.js css png jpg等静态文件的支持。
3.GET POST两种请求方式的支持。
4.目录的支持
5.示例文件中a.php实现一个简单的基于php的计算器。