1 package my.tomcat2; 2 3 import java.io.BufferedWriter; 4 import java.io.IOException; 5 import java.io.OutputStreamWriter; 6 import java.net.Socket; 7 import java.util.Date; 8 9 /** 10 * 用来反馈客户端,也就是想在客户端上显示什么信息 11 */ 12 public class Response { 13 //构建 响应头信息需要的一些小零件,这里可以在网上查看下 HTTP 协议 14 private static final String CRLF = " "; 15 private static final String BLANK = " "; 16 //这里是正文,也就是显示在页面上的信息 17 private StringBuilder context; 18 //这里是构建 响应头信息 19 private StringBuilder headInfo; 20 //因为头信息最后会需要 正文的 字节长度,是字节长度,不是字符长度 21 private int len; 22 //用来反馈到客户端上的 输出流 23 private BufferedWriter bw; 24 private String msg; 25 //状态码,这里如上查询 HTTP 协议 26 private int code; 27 28 //初始化 字段 29 public Response(Socket client) { 30 context = new StringBuilder(); 31 headInfo = new StringBuilder(); 32 try { 33 bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); 34 } catch (IOException e) { 35 code = 500; 36 return ; 37 } 38 } 39 40 41 //构建 响应头部信息 42 public void setHead(int code){ 43 headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK); 44 switch (code) { 45 case 200 : headInfo.append("OK").append(CRLF); 46 break; 47 48 case 404 : headInfo.append("NOT FOUND").append(CRLF); 49 break; 50 51 case 500 : headInfo.append("SERVER ERROR").append(CRLF); 52 break; 53 } 54 headInfo.append("Server:Feng server/0.01").append(CRLF); 55 headInfo.append("Date:").append(new Date()).append(CRLF); 56 headInfo.append("Content-type:text/html;charset=utf-8").append(CRLF); 57 headInfo.append("Content-Length:" + len).append(CRLF); 58 headInfo.append(CRLF); 59 } 60 61 //反馈给 客户端 的信息 62 public void print(String msg){ 63 context.append(msg); 64 len += msg.getBytes().length; 65 } 66 67 public void println(String msg){ 68 context.append(msg).append(CRLF); 69 len += (msg+CRLF).getBytes().length; 70 } 71 72 //将 响应头信息+正文 通过流传给 客户端 73 public void pushToClient(int code){ 74 if(context == null){ 75 code = 500; 76 } 77 this.setHead(code); 78 String responseInfo = headInfo.append(context).toString(); 79 try { 80 bw.write(responseInfo); 81 bw.flush(); 82 } catch (IOException e) { 83 return ; 84 } finally { 85 CloseUtil.close(bw); 86 } 87 } 88 }