手写一个简易的tomcat服务器

手写一个简易的tomcat服务器,进一步了解tomcat


提示:以下是本篇文章正文内容,下面案例可供参考

一、开启一个scoket服务,循环接受请求

代码如下(示例):

package com.smallfatcat.server;

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

/**
 * @author zsz
 * 开启socket服务
 * @date 2022/9/3
 */
public class MyHttpServer {
    //设置默认端口 8080
    private int port = 8080;

    //定义一个接受请求的方法
    public void receicing(){
        try {
            //创建socket服务
            ServerSocket serverSocket = new ServerSocket(port);
            //循环接受请求
            while (true){
                //获取连接对象
                Socket socket = serverSocket.accept();
                //通过输入流获取链接对象
                //创建一个request请求
                InputStream inputStream = socket.getInputStream();
                MyHttpRequest request = new MyHttpRequest(inputStream);
                //解析请求
                request.parse();
                //创建一个response响应
                OutputStream outputStream = socket.getOutputStream();
                MyHttpResponse response = new MyHttpResponse(outputStream);
                //进行响应
                response.sendRedirect(request.getUri());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

二、封装一个request对象,处理请求信息

代码如下(示例):

package com.smallfatcat.server;

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

/**
 * @author zsz
 * 封装请求,处理请求相关的业务
 * @date 2022/9/3
 */
public class MyHttpRequest {

    private InputStream inputStream;
    private String uri;

    public MyHttpRequest(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    //解析输入流里面的信息
    public void parse(){
        try {
            //将inputStream里面的数据读取到字节数组里面
            byte[] bytes = new byte[1024];
            inputStream.read(bytes);
            String request = new String(bytes);
            //调用方法获取uri
            parseUri(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //通过输入流获取的信息解析字符串里面的uri
    public void parseUri(String request){
        //通过查找空格
        int index1,index2;
        index1 = request.indexOf(" ");
        index2 = request.indexOf(" ",index1 + 1);
        //通过字符串的substring截取方法截取uri
        uri = request.substring(index1 + 1,index2);
        System.out.println(uri);
    }
    //获取uri
    public String getUri(){
        return this.uri;
    }
}

三、封装一个response对象,处理响应信息

代码如下(示例):

package com.smallfatcat.server;

import java.io.*;

/**
 * @author zsz
 * 封装响应,处理响应相关的业务
 * @date 2022/9/3
 */
public class MyHttpResponse {
    private OutputStream outputStream;

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

    public void sendRedirect(String uri){
        //判断目标资源是否存在
        //不存在返回404
        //存在直接返回目标资源数据
        //System.getProperty("user.dir") 获取路径
        File file = new File(System.getProperty("user.dir") + "/src/main/resources/static" + uri);
        if(file.exists()){
            //返回目标资源数据--先通过io流读取本地数据--再通过输出流输出
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] bytes = new byte[(int)file.length()];
                fileInputStream.read(bytes);
                String result = new String(bytes);
                String response = getResponseMessage("200", result);
                this.outputStream.write(response.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else {
            try {
                //返回404
                String error = getResponseMessage("404","404 File Not Found");
                this.outputStream.write(error.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //获取响应格式--必须按照特定的格式进行处理响应
    public String getResponseMessage(String code,String message){
        return "HTTP/1.1 " + code + "\r\n"
                + "Content-Type: text/html\r\n"
                + "Content-Length: " + message.length()
                + "\r\n"
                + "\r\n"
                + message;
    }
}

四、创建一个测试类,测试–访问某个资源,如果本地存在该资源则返回该资源,如果不存在则返回404

代码如下(示例):

package com.smallfatcat.test;

import com.smallfatcat.server.MyHttpServer;

/**
 * @author zsz
 * @Description
 * @date 2022/9/3
 */
public class Test {
    public static void main(String[] args) {
        System.out.println("Server startup successfully");
        MyHttpServer server = new MyHttpServer();
        server.receicing();
    }
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

typedef love

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值