模拟Tomcat服区器(简易版)

模拟Tomcat服区器

原理分析

Get方式

请求行

GET /index.html HTTP/1.1

请求头 key: value

Host: localhost:801 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3 Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9 Cookie: Idea-905e6cbc=709bfabc-875e-4542-8f0f-5dd05f46e6a4

post方式

请求行 状态码 200 ok 400客户端

请求头

Context—length

空行

请求体

image-20200907165758590

响应之前需要把格式写到网络里面

例如文本类型 编码

响应行 协议版本 状态码 状态英文 要换行

键值对形式存(响应类型context-type)

空行

响应体

image-20200907165847611

Application类

public class Application {
   public static void main(String[] args) throws IOException {
       //创建服务端
       ServerSocket serverSocket = new ServerSocket(9999);
       ExecutorService Threadpool = Executors.newCachedThreadPool();
       Request request=null;
       while (true){
           Socket socket = serverSocket.accept();
           //把socket转为对象
            request = socketto.gterequse(socket);
           String filename1 =request.getRequestresourse();///1.txt
           Response response = new Response();
           String filename=filename1.substring(1);
          System.out.println("filename"+filename+"&&&&&&&&");
           File file = new File(filename);
           if (file.exists()){
               response.setStateCode(StateCode.OK);
          }else{
               response.setStateCode(StateCode.Not_found);
          }
           String suff=filename.substring(filename.lastIndexOf(".")+1);
           response.getMap().put("ContentType: ", FileTypeUtil.map.get(suff));
//           System.out.println(response.toString());
//           System.out.println(request.toString());
//           System.out.println("--------"+suff);
           //多线程处理对象
           poolAction.getThread(Threadpool,response,socket,filename);

      }

  }
}

Request

@Data
public class Request implements Serializable {

  //设置请求方式
  private String requestMethod;
  //获取请求的资源
  private String requestresourse;
  //存放请求的电脑的信息




}

Response

@Data
public class Response implements Serializable{
      //响应头
      private String argement="HTTP/1.1";
      //状态码
      private StateCode stateCode;
      //响应体的封装
      private Map<String,String> map = new HashMap<>();


}

FileTypeUtil

public class FileTypeUtil {
   public  static Map<String,String> map = null;
   static {
       map=new HashMap<>();
       map.put("txt","text/html,charset =utf-8" );
       map.put("html","text/html,charset =utf-8" );
       map.put("jpg","image/jpeg,charset =utf-8" );
       map.put("pdf","application/pdf,charset =utf-8" );
       map.put("png","image/png,charset =utf-8" );


  }

}

PoolAction

public class poolAction {
   public static void  getThread(ExecutorService Threadpool, Response response, Socket socket,String filename){
       Threadpool.execute(()->{
           try {
               StringBuffer stringBuffer=null;
               String contexttype=null;
               BufferedOutputStream bf = new BufferedOutputStream(socket.getOutputStream());

               //System.out.println(filename);
               bf.write((response.getArgement()+" ").getBytes());
               bf.write((StateCode.OK.getId()+" "+response.getStateCode().toString()+"\r\n").getBytes());
               Set<Map.Entry<String, String>> entries = response.getMap().entrySet();
               for (Map.Entry e:entries
                    ) {
                  contexttype= e.getValue()+" "+e.getValue()+"\r\n";
              }
               bf.write(contexttype.getBytes());
               bf.write("\r\n".getBytes() );
               FileInputStream fileInputStream = new FileInputStream(filename);
               byte [] bytes = new byte[1024];
               int hasread=-1;
               while ((hasread=fileInputStream.read(bytes))!=-1){
                   bf.write(bytes,0 ,hasread );
              }
               fileInputStream.close();
               bf.flush();
               fileInputStream.close();
               socket.shutdownOutput();
          } catch (IOException e) {
               e.printStackTrace();
          }
      });

  }
}

socketto

public class socketto {
   public static Request gterequse(Socket socket) throws IOException {
       Request request = new Request();
       BufferedReader  bReader= new BufferedReader(new InputStreamReader(socket.getInputStream()));
       String[] split = bReader.readLine().split(" ");
//       System.out.println(Arrays.toString(split));
       request.setRequestMethod(split[0]);
       request.setRequestresourse(split[1]);
//       System.out.println(request.getRequestresourse());
//       System.out.println(request.getRequestMethod());
//       String hasread =null;
//       while((hasread=bReader.readLine())!=null) {
//           String[] split1 = hasread.split(": ");
//           request.getRequestMap().put(split1[0],split1[1]);
//           System.out.println("----------------");
//       }

//       socket.shutdownInput();
       return request;
  }
}

StateCode

public enum StateCode {
   OK(200, "OK"), Not_found(404, "not_found");

   private int id;
   private String msg;

   private StateCode(int id, String state) {
       this.id = id;
       this.msg = state;
  }

   public int getId() {
       return id;
  }

   public void setId(int id) {
       this.id = id;
  }

   public String getMsg() {
       return msg;
  }

   public void setMsg(String msg) {
       this.msg = msg;
  }
}

idea源码地址:https://github.com/cqf073/Tomcat_service(内附设计模式源码)

posted @ 2020-09-08 17:20  乘清风  阅读(298)  评论(0编辑  收藏  举报