一直不理解Http协议,觉得很抽象很神秘,看 《how tomcat work》时看到搭建了一个简单的http服务器,发现协议其实就是对消息格式的规范,就是大家都按这个规范约定的格式发消息收消息。
1.建立sockerserver服务
2.监听相应端口
3.对监听到的字节进行解析
Request 实际上就是解析HTTP协议并得到资源的请求路径uri。
private String parseUri(String 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;
}
4.对请求进行响应
这里实际上根据request分析的uri进行资源的字节化,输出到socket的out
"<h1>File Not Found</h1>";
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();
}
}
可以看到其实就是简单的将资源用字节流输出。
最后提供完整的代码包(http://download.csdn.net/source/3194644),运行HttpServer.java 后可以通过浏览器访问:http://localhost:8088/index.htm 可以看到静态页面,通过后台可以看到请求的Http信息。