最近在读《深入剖析Tomcat》这本书,书中附带了很多源码帮助学习.
但是部分源码存在一些小问题需要修复才可以正常运行.
另外有些源码的运行方式也需要特殊注意.
后来发现github上有现成的可运行的代码集合:
vonzhou/HowTomcatWorks
我这里就继续做一些代码的解读吧
第一章
如下图所示,代码清单1-6中直接发送了响应体,缺失了http响应头,需要补充.否则http请求会失败.
修改后的代码:
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
PrintWriter printWriter = new PrintWriter(output);
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type:text/html;charset=utf-8");
printWriter.println("Content-length: " + file.length());
printWriter.println();
printWriter.flush();
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);
}
printWriter.close();
} else {
output.write(errorMessage.getBytes());
}
} catch (Exception e) {
System.out.println(e.toString());
output.write(errorMessage.getBytes());
} finally {
if (fis != null) {
fis.close();
}
}
}
第二章
- PrimitiveServlet.class需要放在webroot目录下,并且最好不要携带package信息,否则需要在webroot目录下建立package的目录.不然会ClassNotFoundException.
- PrimitiveServlet.service()同样需要补充http响应头.
- 在webroot下手动编译PrimitiveServlet(需要有servlet-api.jar):
javac -classpath servlet-api.jar PrimitiveServlet.java
第三章
SocketInputStream的read方法是这样的:
public int read()
throws IOException {
if (pos >= count) {
fill();
if (pos >= count)
return -1;
}
// 将有符号的byte转换为无符号类型
return buf[pos++] & 0xff;
}
数组buf里面存储的就是http的请求信息,令人比较好奇的是 buf[pos++] & 0xff 的作用是什么。后来查阅了一些资料,知道了作用是将有符号的byte转换为无符号类型,可以将值域从[-128,127]转为[0,255]。
Java中byte做&0xff运算的原因及解析
java中byte与int的转换原理