TomCat是常用的Web容器,我也使用了快一年了,但是平时出错的时候总是摸不着头脑,错误日志看不懂就抓瞎,所以这次看借着这本经典的书来看一看Tomcat的源码,希望能有所进步。
第一章是搭建一个简单的Web Server
public class HttpServer {
...
public static void main(String[] args) {
HttpServer server = new HttpServer();
//等待被调用
server.await();
}
public void await() {
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 {
//Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.
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(用accepte函数)
- 然后获取InputStream与OutputStream
- 用inputstream构造request,然后调用它的prase函数,获取uri
用outputstream构造response,调用其sendStaticResource函数,将uri指向的资源获取到,并读取之
这就是一个简单的Web Server的工作流程。