Listing 2.2. HttpServer1 类的 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);
}
// 循环,等待一个请求
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
// 创建请求对象并解析
Request request = new Request(input);
request.parse();
// 创建回应对象
Response response = new Response(output);
response.setRequest(request);
//检测是否是 servlet 或静态资源的请求
//servlet 请求以 "/servlet/" 开始
if (request.getUri().startsWith("/servlet/")) {
ServletProcessor1 processor = new ServletProcessor1();
processor.process(request, response);
}
else {
StaticResourceProcessor processor =
new StaticResourceProcessor();
processor.process(request, response);
}
// 关闭socket
socket.close();
//检测是否前面的 URI 是一个 shutdown 命令
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
public Object getAttribute(String attribute) {
return null;
}
public Enumeration getAttributeNames() {
return null;
}
public String getRealPath(String path) {
return null;
}
public PrintWriter getWriter() {
// autoflush is true, println() will flush,
// but print() will not.
writer = new PrintWriter(output, true);
return writer;
}
Listing 2.3.StaticResourceProcessor 类的 process方法。
public void process(Request request, Response response) {
try {
response.sendStaticResource();
}
catch (IOException e) {
e.printStackTrace();
}
}
petrel ,java 爱好者,在深圳从事 java 和数据库的开发工作,喜爱各项运动!可以通过petrel.zhang@ccjk.com 与她联系.也可以点击http://www.matrix.org.cn/user_view.asp?username=petrel查看她的信息.进入讨论组讨论。
(出处:http://www.VeVb.com)
新闻热点
疑难解答