he 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,源码如下:
Insert title here
?Hello World!
现在启动该WEB服务器,并请求index.html静态页面。

所对应的控制台的输出:

如此,一个简单的http服务器便完成了。