1.按照HTTP协议要求,与客户端完成一次交互流程为一问一答,因此分为三步:
1:解析请求 目的:将浏览器发送的请求内容读取并整理 2:处理请求 目的:根据浏览器的请求进行对应的处理工作 3:发送响应 目的:将服务端的处理结果回馈给浏览器
public class ClientHandler implements Runnable { private static File dir; private static File staticDir; //静态需要初始化 需要在静态块中初始化 static { try{ dir =new File( //IDEA中执行项目时,类加载路径是从target/classes开始的 定位环境变量ClassPath(类加载路径)中"."的位置 ClientHandler.class.getClassLoader().getResource(".") .toURI()); //定位到了target/classes/static目录 staticDir = new File(dir,"static"); System.out.println("static是否存在:"+staticDir.exists()); }catch(URISyntaxException e){ e.printStackTrace(); } } private Socket socket; //建立一个插口 连连接客户端 客户端的信息发到这里来 public ClientHandler(Socket socket){ this.socket= socket; } public void run(){ try{ //1.解析请求,实例化请求对象的过程就是解析的过程 HttpServletRequest request=new HttpServletRequest(socket); //2.处理请求 String path = request.getUri(); System.out.println("请求对象路径:"+path); File file = new File(staticDir,path); String line; if(file.isFile()){ //看访问的网址是否是个文件 1.发送状态行 line = "HTTP/1.1 200 OK"; }else { line = "HTTP/1.1 400 NotFound"; file = new File(staticDir,"/root/404.html") ; } //吧写出的直接发送出去 //3.发送的正文 println(line); //发送响应头 2.发送响应头 这俩个 println("Content-Type: text/html"); println("Content-Length: "+file.length()); println(""); //发送响应正文(index.html页面的所有数据) 进行输出 FileInputStream fis = new FileInputStream(file); OutputStream out =socket.getOutputStream(); byte[] buf = new byte[1024*10]; int len = 0; while((len =fis.read(buf))!=-1){ out.write(buf,0,len); } } catch (IOException e) { e.printStackTrace(); }finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } //本版本测试 将resources下的static目录中的index.html响应给 //世纪虚拟机执行查看的是target/class目录下的内容 //maven项目斌以后会将src/main/java和src/main/resources //因此实际需要定位的是target中的classes/static/index.html private void println(String line ) throws IOException{ OutputStream out =socket.getOutputStream(); byte[] data = line.getBytes(StandardCharsets.ISO_8859_1); out.write(data); //回车符:13与换行符:10 out.write(13); out.write(10); } }