手写一个mini版的tomcat

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname Tomcat
 * @Description TODO
 * @Date 2022/8/19 9:35
 * @Author: X.I.O
 */
public class Tomcat {
	
	       /**
         * 1. url 映射的反射类
         * 2. 建议映射一个对象,对象至少包含四个属性,反射实体类,反射类实例,实体类要执行的方法,要执行方法的参数个数的反射数组Class<?>[] clazz
         *      通过 Object result=method.invoke(‘反射类实例’,'反射类实方法需要的参数')
         *      获取 反射类实方法需要的参数:
         *                  Class<?>[] clazzs=method.getParameterTypes()
         *
         */
    public static Map<String,String> urlServletMap=new HashMap<>();

    static {
        urlServletMap.put("/tomcat","demo");
    }

    public static void main(String[] args) {
        start();
    }

    public static void start(){
        int port=8080;
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            while (true) {
                Socket socket=serverSocket.accept();
                InputStream inputStream=socket.getInputStream();
                OutputStream outputStream=socket.getOutputStream();

                Map<String,Object> reqMap=getRequestInfo(inputStream);
                String url=(String) reqMap.get("url");
                String method=(String)reqMap.get("method");
                if(method.equalsIgnoreCase("GET") && url.equals("/tomcat")){
                    JSONObject obj=new JSONObject();
                    obj.put("key","word");
                    respWirteJson(outputStream,obj.toJSONString());
                }
                socket.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String,Object> getRequestInfo(InputStream inputStream) throws IOException {
        Map<String,Object> stringMap=new HashMap<>();
        String httpRequest="";
        byte[] httpRequestBytes = new byte[1024];
        int length=0;
        if((length=inputStream.read(httpRequestBytes))>0){
            httpRequest=new String(httpRequestBytes,0,length);
        }
        System.out.println(httpRequest);
        String httpHead=httpRequest.split("\n")[0];
        String url=httpHead.split("\\s")[1];
        String method=httpHead.split("\\s")[0];
        stringMap.put("method",method);
        if(url.contains("?")){
            url=url.substring(0,url.lastIndexOf("?"));
        }
        stringMap.put("url",url);
        String[] httpHeads=httpRequest.split("\n");
        //请求体
        Map<String,String> request=new HashMap<String, String>();
        //请求参数
        Map<String,Object> params=new HashMap<String, Object>();
        boolean starthead=true;
        for (int i = 0; i < httpHeads.length; i++) {
            String str=httpHeads[i];
            if(str.contains("{")){
                starthead=false;
            }
            if(str.contains("}")){
                starthead=true;
            }
            //处理请求头
            if(starthead && str.contains(": ")){
                String[] str1=str.split(": ");
                if(str1.length==2){
                    System.out.println(str1[0]+"  "+ str1[1]);
                    request.put(str1[0],str1[1]);
                }
            }
            //处理json数据
            if(!starthead && str.contains(": ")){
                String[] str1=str.split(": ");
                if(str1.length==2){
                    String key=replaceTirm(str1[0]);
                    String value=replaceTirm(str1[1]);
                    params.put(key,value);
                }
            }
        }
        stringMap.put("heads",request);

        //截取请求参数
        if("GET".equalsIgnoreCase(method)){
            String paramStr=url.substring(url.lastIndexOf("?")+1);
            String[] paramsArray=paramStr.split("&");
            for (int i = 0; i < paramsArray.length; i++) {
                String param=paramsArray[i];
                String[] paramStrArray=param.split("=");
                if(paramStrArray.length==2){
                    params.put(paramStrArray[0],paramStrArray[1]);
                }
            }
        }
        stringMap.put("params",params);
        return stringMap;
    }

    /**
     * 写出json 数据给前端
     * @param outputStream
     * @param content
     * @throws IOException
     */
    public static void respWirteJson(OutputStream outputStream,String content) throws IOException {
        StringBuffer httpResonse=new StringBuffer();
        httpResonse.append("HTTP/1.1 200 OK\n")
                .append("Content-Type: application/json; charset=utf-8 \n")
                .append("\r\n")
                .append(content);
        outputStream.write(httpResonse.toString().getBytes());
        outputStream.close();
    }

    /**
     * 写出html数据
     * @param outputStream
     * @param content
     * @throws IOException
     */
    public static void respWirteHtml(OutputStream outputStream,String content) throws IOException {
        StringBuffer httpResonse=new StringBuffer();
        httpResonse.append("HTTP/1.1 200 OK\n")
                .append("Content-Type: text/html \n")
                .append("\r\n")
                .append("<html><body>")
                .append(content)
                .append("<body></html>");
        outputStream.write(httpResonse.toString().getBytes());
        outputStream.close();
    }

	//json数据解析,去除左右两边空格
    public static String replaceTirm(String content){
        if (null== content || "".equals( content)){
            return  content ;
        }
        String regexL = "^[ *|\\s*]*";
        String regexR=" [ *|\\s*]* $";
        return content.replaceAll( regexL,"").replaceAll( regexR ,"");
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值