基于tcp自己实现简单的HTTP服务器

来源:互联网 发布:深圳网络金融公司 编辑:程序博客网 时间:2024/06/06 03:55

1、解析:在浏览器中输入url向服务器提交一个请求,服务器接受到一窜字符串,之后便可以从中提取出一个重要的信息 uri 【/tiger.html】GET /tiger.html HTTP/1.1,服务器便可以根据客户端提交的uri对其进行反馈,利用字节输出流将uri资源拼凑为http协议的格式输出到浏览器显示。

2、代码演示如下:

package com.linjitai.http;import java.io.*;import java.net.*;/** * 自己实现HTTP * 1、针对http协议请求部分进行解释 * 2、做出相应http协议响应部分的实现 * 注:资源文件放在字节码文件目录页下 * @author tiger * @time 2017年8月28日 */public class MyHTTP {public final static int PORT = 8080;public static void main(String[] args) throws Exception {System.out.println("MyHTTP listening......");try {ServerSocket server = new ServerSocket( PORT );while (true) {//获取套接字Socket socket =  server.accept();service(socket);}} catch (IOException e) {e.printStackTrace();}}/** * http服务器 * @param socket * @throws Exception */public static void service(Socket socket) throws Exception{//获取输入流InputStream is = socket.getInputStream();Thread.sleep(500);//提取用户提交的数据byte[] buff = new byte[is.available()];//将读取客户端请求的数据存入buff中is.read(buff);//将字节转换成字符String httpReq = new String(buff,"UTF-8");if(httpReq != null && !httpReq.isEmpty()){System.out.println(httpReq);//解析获取到的请求参数String[] requests = httpReq.split("\n");String[] firstLines = requests[0].split(" ");String uri = firstLines[1];/*-------------------响应浏览器start-----------------------*/OutputStream os = socket.getOutputStream();if (uri.indexOf("favicon.ico")==-1) {if (uri.indexOf("servlet") == -1) {//响应的是静态资源String respFirstLine = "HTTP/1.1 200 OK\r\n";//响应头部String head = "Content-Type: text/html\r\n\r\n";//响应体,资源文件放在项目classes[字节码文件]下InputStream fis = MyHTTP.class.getResourceAsStream("root/" + uri);//输出响应的第一行os.write(respFirstLine.getBytes());//输出响应的头部信息os.write(head.getBytes());//输出响应bodybyte[] buffos = new byte[24];int len = 0;//边读边写到浏览器while ((len = fis.read(buffos)) != -1) {os.write(buffos,0,len);}//关闭文件流fis.close();}else {//响应的是Servlet类//过滤是post还是get方法提交if(uri.indexOf("?")!=-1){uri=uri.substring(uri.indexOf("servlet/")+8,uri.indexOf("?"));}else{uri=uri.substring(uri.indexOf("servlet/")+8, uri.length());}//同一个接口,不同的实现Servlet servlet = (Servlet) Class.forName("com.linjitai.http."+uri).newInstance();servlet.sercvice(buff, os);}is.close();/*-------------------响应浏览器end-----------------------*/}Thread.sleep(1000);socket.close();}}}

原创粉丝点击