the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


自己动手写Web服务器(一)简单的静态服务器

作者:the5fire | 标签:     | 发布:2011-07-29 10:17 a.m. | 阅读量: 9803, 9666
前几天开始看《How Tomcat Works》,因为有人推荐要研究tomcat源代码,看这本书是很有帮助的。
看到第三章,这几天一直有事,也没心情看,现在想想,别管什么事抽点时间学习,学点是点。
为了续得上思路,需要把原先的内容在搂一遍。

从浏览器使用者的角度来看,我们都知道,打开浏览器,输入网址(URL),得到我们想看到的页面。
任何一个web项目开发者都能够想象的出来,我们的浏览器和我们访问的网站所在的服务器发生了怎样的勾当。

首先,浏览器会根据URL,request的请求,这个请求被服务器上的web服务器接受之后,然后返回html文本给浏览器,
然后浏览器进行渲染显示。对于动态web服务器,还有一个功能就是把动态(如php、jsp、asp)的语言进行解析,最后输出html文本。

另外,网络基础稍微好一点的开发人员也会知道,每一个请求其实就是浏览器想服务器发送了一个http的请求,请求格式有以下三部分组成:

请求方法URI协议/版本
请求头(Request Header)
请求正文

例如:

GET /index.html HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ) AppleWebKit/534.12 (KHTML, like Gecko) Maxthon/3.0 Safari/534.12
Accept-Encoding: gzip,deflate
Accept-Language: zh-CN
Accept-Charset: iso-8859-1,*,utf-8

另外我们也知道,每一个http请求,其实就是socket的一次通信,socket把请求数据发送到web服务器上。

我们知道浏览器这边大概的活动流程了,那么在web服务器那边是怎么运作的呢?它是怎么解析我们发过去的数据的?它又是如何根据我们发送的请求,返回我们需要的资源的?

有了这些个疑问,要了解并实现一个web服务器就顺其自然了,最重要的是有了目的。
根据《How Tomcat Works》第一章,我们实现一个简单的WEB服务器。
大致思路如下:
1、 首先我们应该监听指定端口,如80,或者8080或者其他。
2、 在该端口接受到消息之后开始处理。
3、 根据http协议,我们可以知道在协议的第一行内容中包含了浏览器请求的资源名称以及路径。
4、 根据浏览器请求的资源,找到资源所在,然后通过socket输出到浏览器。


根据上面的思路,我们首先要有一个类来监听某一端口,这个类我们命名为HttpServer.java:

import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File;

/**
* Listening on the port
* @author the5fire learn tomcat
*
*/
public class HttpServer {
/** WEB_ROOT is the directory where our HTML and other files reside.
* For this package, WEB_ROOT is the "webroot" directory under the
* working directory.
* The working directory is the location in the file system
* from where the java command was invoked.
*/
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
// shutdown command
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
// the shutdown command received
private boolean shutdown = false;

public static void main(String[] args) {
HttpServer server = new HttpServer();
server.await();
}

public void await() {
System.out.println(WEB_ROOT);
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port, 1,
InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
// create Request object and parse
Request request = new Request(input);
request.parse();
// create Response object
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
// Close the socket
socket.close();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace ();
continue;
}
}
}
}

另外需要一个Request类来处理服务器的请求,以及一个Response来返回消息给客户端。
Request类的具体作用就是根据客户端发送过来的请求,然后根据消息的内容得到客户端请求的资源:

import java.io.InputStream;
import java.io.IOException;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
// Read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j request.append((char) buffer[j]);
}

uri = parseUri(request.toString());

}

private String parseUri(String requestString) {
System.out.println("requestString:" + requestString);
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
public String getUri() {
return uri;
}
}

Response类的具体作用就是把Request类解析出来的资源路径读取到程序中,然后再输出到客户端:

import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;
/*
HTTP Response = Status-Line
*(( general-header | response-header | entity-header ) CRLF)
CRLF
[ message-body ]
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
else {
// file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"

File Not Found

";
output.write(errorMessage.getBytes());
}
}
catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString() );
}
finally {
if (fis!=null)
fis.close();
}
}
}

然后在你项目所在的路径下面,自己建立一个index.html页面(里面的内容随便是啥都行),然后启动HttpServer这个类,在浏览器中输入:http://localhost:8080/index.html就能看到你index.html中的内容了。

至此一个简单的静态web服务器就完成了,当然现在还是比较简单的,也比较简陋,因为在httpserver并没有处理如果不是http请求的情况。

不过在这本书的后面这个web服务器会逐渐丰满起来。大家不妨自己读一下,到我网站上方的“精品书籍下载”中可以下载这本书,一个是英文版的,是全部。中文版的只有前四章。
- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: