public Response(OutputStream output){ this.output=output; }
public void setRequest(Request request){ this.request=request; }
public void sendStaticResource()throws IOException{ byte[] bytes=new byte[BUFFER_SIZE]; FileInputStream fis=null; try { File file=new File(HttpServer.WEB_ROOT,request.getUri()); if(file.exists()){ fis=new FileInputStream(file); int ch=fis.read(bytes,0,BUFFER_SIZE); while(ch!=-1){ output.write(bytes, 0, BUFFER_SIZE); ch=fis.read(bytes, 0, BUFFER_SIZE); } }else{ //file not found String errorMessage="HTTP/1.1 404 File Not Found
"+ "Content-Type:text/html
"+ "Content-Length:23
"+ "
"+ "<h1>File Not Found</h1>"; output.write(errorMessage.getBytes()); } } catch (Exception e) { System.out.println(e.toString()); }finally{ if(fis!=null){ fis.close(); } } } }Response对象在HttpServer类的await()方法中通过传入套接字中获取的OutputStream来创建。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";