public void run() {
try {
/*
* 需求:模拟tomcat服务器
*/
/*
* 1. 读取请求信息
*/
BufferedReader bfr = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//读取客户端请求头信息
String line = bfr.readLine();
/*
* 2.获取请求路径
*/
String[] str =line.split(" +");
String path= str[1].substring(1);
/*
* 3.将客户端浏览器请求的路径封装为服务器端的File对象
*/
File file = new File(path);
/*
* 4.字节流读取客户端请求服务器端的文件
*/
FileInputStream fis = new FileInputStream(file);
//获取Socket输出流,用于为客户端响应
OutputStream out = socket.getOutputStream();
/*
* 6. 输出http响应头
*/
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write("Server: Apache-Tomcat\r\n".getBytes());
out.write(("Date: "+new Date().toString()+"\r\n").getBytes());
out.write("\r\n".getBytes());
//将请求的文件响应给客户端浏览器
byte[] bytes = new byte[1024];
int len = 0 ;
while((len=fis.read(bytes))!=-1){
out.write(bytes, 0, len);}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
哪里有错误? |
|