手写Tomcat(一) 访问静态资源

tomcat获取客户端请求图:在这里插入图片描述

1、Request类

package request;

import response.Response;

import java.io.IOException;
import java.io.InputStream;

/**
 * version1.0 访问项目下得静态资源
 * 这个类主要是把从socket拿到得输入流解析一下,解析url出来
 *
 */
public class Request {

    private InputStream is;

    //请求路径
    private String url;

    public Request(){

    }

    public Request(InputStream is){
        this.is = is;
    }

    /**
     * 解析url
     */
    public void parse(){
        StringBuffer request = new StringBuffer(Response.BUFFER_SIZE);

        byte[] buffer = new byte[Response.BUFFER_SIZE];

        int i = 0;
        try{
            i = is.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (int j = 0; j < i; j++) {
            request.append((char)buffer[j]);
        }
        System.out.println(request.toString());
        this.url = parseUrl(request.toString());
    }


    /**
     *
     * @param request
     * @return
     */
    private String parseUrl(String request) {
        int index1,index2;
        //查看socket获取的请求头是否有值
        index1 = request.indexOf(' ');
        if (index1 != -1){
            index2 = request.indexOf(' ', index1 + 1);
            if (index2 > index1){
                return request.substring(index1 + 1,index2);
            }
        }
        return null;
    }

    public String getUrl(){
        return url;
    }
}

2、Response类

package response;

import request.Request;

import java.io.*;


public class Response {

    public static final Integer BUFFER_SIZE = 2048;

    private static final String WEB_ROOT = "D:";

    private Request request;

    private OutputStream outputStream;

    public Response(OutputStream outputStream){
        this.outputStream = outputStream;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException{
        byte[] buffer = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        File file = new File(WEB_ROOT,request.getUrl());
        String returnMsg = null;
        try {
            if(file.exists() && !file.isDirectory()){
                fis = new FileInputStream(file);
                StringBuilder sb = new StringBuilder();
                int length;
                while ((length = fis.read(buffer,0,buffer.length)) != -1){
                    sb.append(new String(buffer,0,length,"gbk"));
                }
                returnMsg = "HTTP/1.1 200 OK\r\n" +
                            "Content-Type: text/html \r\n" +
                            "Content-Length: "+sb.length()+"\r\n"+
                            "\r\n"+
                            sb.toString();
            }else{
                String errorMsg = "<h1>" + file.getName() + " file or directory not exists</h1>";
                returnMsg = "HTTP/1.1 404 File Not Fount\r\n" +
                        "Content-Type: text/html \r\n" +
                        "Content-Length: "+errorMsg.length()+"\r\n"+
                        "\r\n"+
                        errorMsg;
            }
            outputStream.write(returnMsg.getBytes());
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                fis.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

}

3、HTTPServer类

package server;

import request.Request;
import response.Response;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HTTPServer {

    public void acceptWait() throws IOException {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8080, 3, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true){
            try {
                Socket socket = serverSocket.accept();
                InputStream is = socket.getInputStream();
                OutputStream os = socket.getOutputStream();

                Request request = new Request(is);
                request.parse();

                Response response = new Response(os);
                response.setRequest(request);
                response.sendStaticResource();

                socket.close();
            }catch (IOException e){
                e.printStackTrace();
                continue;
            }
        }
    }
}

4、Main启动类

import server.HTTPServer;

import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException {
        HTTPServer httpServer = new HTTPServer();
        httpServer.acceptWait();
    }
}

  • http请求
    在这里插入图片描述

  • http响应
    在这里插入图片描述
    把以前同事的文章抄过来水一水,模拟tomcat访问静态资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值