Tomcat1.0及2.0

1、封装响应头

public class ResponseHeaderUtil {

    public static String getHeader200Str(long contentLength){
        return "HTTP/1.1 200 OK \n" +
                "Content-Type: text/html \n" +
                "Content-Length: " + contentLength + " \n" +
                "\r\n";
    }

    public static String getHeader404Str(){
        String str = "<h1>404 not found</h1>";
        return "HTTP/1.1 404 not found \n" +
                "Content-Type: text/html \n" +
                "Content-Length: " + str.getBytes().length + " \n" +
                "\r\n";
    }
}

2、启动类 Bootstrap

public class Bootstrap {

    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * 只有返回信息
     * @throws IOException
     */
    public void start() throws IOException {
        System.out.println("tomcat 开始启动.......");
        ServerSocket serverSocket = new ServerSocket(port);
        while (true){
            Socket socket = serverSocket.accept();
            String content = "hello tomcat!!!";
            String responseText = ResponseHeaderUtil.getHeader200Str(content.getBytes().length) + content;
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(responseText.getBytes());
            outputStream.close();
        }
    }
public static void main(String[] args) throws IOException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.start();
    }
}

2、读取参数

public void start() throws IOException {
        System.out.println("tomcat 开始启动.......");
        ServerSocket serverSocket = new ServerSocket(port);
        while (true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            int count = 0;
            while (count == 0){
                count = inputStream.available();
            }
            byte[] bytes = new byte[count];
            inputStream.read(bytes);
            String str = new String(bytes);
            System.out.println(str);
        }
    }

猜你喜欢

转载自blog.csdn.net/xingcsdnboke/article/details/129689438
今日推荐