Tomcat1.0及2.0

该代码示例展示了如何用Java创建一个简单的HTTP服务器,处理200和404响应。Bootstrap类用于启动服务器并监听指定端口,当接收到请求时,返回预设的HTTP响应头和内容。ResponseHeaderUtil工具类用于构建HTTP响应头。
摘要由CSDN通过智能技术生成

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);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值