HttpWeb服务器之--用OO方式写
虽然写的不是很好,但最终解释权以及版权归13东倍所有!
package com.web;import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {new HttpWeb();}
}
package com.web;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class HttpWeb {private static int port=8880;private boolean isRun=true;public HttpWeb() throws IOException{//System.out.println("coming HttpWeb()");ServerSocket listening=new ServerSocket(port);System.out.println("listening监听的端口号---"+listening.getLocalPort());while(isRun){System.out.println("loop");Socket socket=listening.accept();System.out.println("socket---"+socket);Request request=new Request(socket.getInputStream());//request.getURI();Response response=new Response(socket.getOutputStream());//response.outHTML(request.getURI());WebProcess wp=new WebProcess(request,response);//wp.returnFile();response.outHTML(wp.returnFile());socket.close();}}}
package com.web;import java.io.IOException;import java.io.InputStream;import java.io.BufferedReader;import java.io.InputStreamReader;public class Request {private InputStream inputStream=null;public Request(InputStream inputStream) {this.inputStream=inputStream;}public String getURI() throws IOException{String resource=null;BufferedReader in=new BufferedReader(new InputStreamReader(inputStream));System.out.println("in----------"+in);String line=in.readLine();System.out.println("line---------"+line);resource=line.substring(line.indexOf("/")+1,line.lastIndexOf("/")-5);System.out.println("resource---------"+resource);return resource;}
}
package com.web;import java.io.OutputStream;import java.io.PrintWriter;public class Response {private PrintWriter out=null;public Response(OutputStream outputStream) {out=new PrintWriter(outputStream,true);}public void outHTML(String datas){System.out.println("coming outHTML()");out.println(datas);}
}
package com.web;import java.io.File;import java.io.FileInputStream;import java.io.IOException;public class WebProcess {private Request request=null; private Response response=null;public WebProcess(Request request, Response response) {this.request=request;this.response=response;}public String returnFile() throws IOException{String resource=request.getURI();File file=new File(resource);System.out.println("file-----------"+file);FileInputStream fis=new FileInputStream(file.getAbsolutePath());System.out.println("fis----------"+fis);byte[] data=new byte[fis.available()];fis.read(data);String datas=new String(data);return datas;}
}