Response类有两个公共方法:setRequest()和sendStaticResource(),setRequest()方法会接收一个Request对象为参数,sendStaticResource()方法用于发送一个静态资源到浏览器,如Html文件。
HttpServer:
package cn.com.server;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
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 invoke.
*/
public static final String WEB_ROOT=System.getProperty("user.dir")+File.separator+"webroot";
private static final String SHUTDOWN_COMMAND="/SHUTDOWN";
private boolean shutdown=false;
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 (Exception e) {
e.printStackTrace();
System.exit(0);
}
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();
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
}
这个类表示一个Web服务器,这个Web服务器可以处理对指定目录的静态资源的请求,该目录包括由公有静态变量final WEB_ROOT指明的目录及其所有子目录。
现在在webroot中创建一个html页面,命名为index.html,源码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
现在启动该WEB服务器,并请求index.html静态页面。
所对应的控制台的输出:
如此,一个简单的http服务器便完成了。