美文网首页
《深入剖析tomcat》 [1]

《深入剖析tomcat》 [1]

作者: 老林_ | 来源:发表于2021-05-28 11:47 被阅读0次

简单的Web服务器

使用三个类 HttpServer用来创建ServerSocket,Response用来接收Request和向客户端返回信息,Request处理客户端传来的信息
HttpServer.java

package com.ly2;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
    public static final String WEB_ROOT=
            System.getProperty("user.dir")+ File.separator
            +"webroot";
    private static final String SHUTDOWN_COMMAND="/SHUTDOWN";

    private boolean shutdown=false;

    public static void main(String[] args) {
        System.out.println(WEB_ROOT);
        HttpServer server=new HttpServer();
        server.await();
    }

    private void await() {
        int port=8080;
        try(ServerSocket serverSocket =new ServerSocket
                (port,1, InetAddress.getByName("127.0.0.1"))){
            while (!shutdown){
                try(Socket socket=serverSocket.accept()) {
                    InputStream inputStream=socket.getInputStream();
                    OutputStream outputStream=socket.getOutputStream();
                    //处理输入
                    Request request=new Request(inputStream);
                    //解析HTTP请求的原始数据
                    request.parse();

                    Response response=new Response(outputStream);
                    response.setRequest(request);
                    response.sendStaticResource();

                    shutdown=request.getUri().equals(SHUTDOWN_COMMAND);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }
    }
}

Request.java

package com.ly2;

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

public class Request {
    private InputStream input;
    private String uri;

    public Request(InputStream inputStream) {
        this.input=inputStream;
    }

    public void parse() {
        StringBuffer request=new StringBuffer(2048);
        int i;
        byte[] buffer=new byte[2048];
        try{
            //这里返回读取的实际字节的大小
            i=input.read(buffer);
        }catch (IOException e){
            e.printStackTrace();
            i=-1;
        }
        for(int j=0;j<i;j++){
            request.append((char)buffer[j]);
        }
        System.out.println(request.toString());
        uri=parseUri(request.toString());
    }

    /**
     * 获取uri
     * @param requestString
     * @return
     */
    private String parseUri(String requestString){
        int index1,index2;
        index1=requestString.indexOf(' ');
        if(index1 != -1){
            index2=requestString.indexOf(' ',index1+1);
            if(index2 > index1){
                //截取http请求的rui
                return requestString.substring(index1+1,index2);
            }
        }
        return null;
    }

    public String getUri() {
        return uri;
    }
}

Response.java

package com.ly2;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response {
    private static final int BUFFER_SIZE=1024;
    Request request;
    OutputStream output;

    public Response(OutputStream outputStream) {
        this.output=outputStream;
    }

    public void setRequest(Request request) {
        this.request=request;
    }

    public void sendStaticResource() throws IOException {
        byte[] bytes=new byte[BUFFER_SIZE];
        FileInputStream fis=null;
        try {
            File file=new File(HttpServer.WEB_ROOT,request.getUri());
            if(file.exists()){
                fis=new FileInputStream(file);
                int ch=fis.read(bytes,0,BUFFER_SIZE);
                //注意 这里一定要添加响应返回头信息,否则chrome不无打开,
                //会出现ERR_INVALID_HTTP_RESPONSE
                String head="HTTP/1.1 200 OK\r\n"+
                        "Content-Type: text/html\r\n\r\n";
                output.write(head.getBytes());
                while (ch!=-1){
                    output.write(bytes,0,ch);
                    //一次性读取部分字节
                    ch=fis.read(bytes,0,BUFFER_SIZE);
                }
                output.flush();
            }else {
                //文件不存在
                String errorMessage="HTTP/1.1 404 FileNot Found\r\n"+
                        "Content-Type: text/html\r\n"+
                        "Content-Length:23\r\n"+
                        "\r\n"+
                        "<h1>File Not Found</h1>";
                output.write(errorMessage.getBytes());
            }
        }catch (Exception e){
            System.out.println(e.toString());
        }finally {
            if(fis!=null){
                fis.close();
            }
        }
    }
}

相关文章

网友评论

      本文标题:《深入剖析tomcat》 [1]

      本文链接:https://www.haomeiwen.com/subject/kcajsltx.html