学习笔记-简易服务器实现

简单实现

  • BootStrap
public class BootStrap{
    public static void main(String[] args){
        ServiceSocket server = new ServerSocket();
        // 监听 8888端口
        server.bind(new InetSocketAddress(8888));
        System.out.println("服务器启动:8888");
        while(true){
            Socket accept = server.accept();
            InputStream inputStream = accept.getInputStream();
            byte[] buffer = new byte[2048];
            int len = inputStream.read(buffer);
            System.out.println(new String(buffer,0,len));
            
            // 拼接一个响应
            String html = "<h1>xxx</h1>"
            String response = "http/1.1 200 ok\r\n"                     // 请求行
                + "content-Type: text/html\r\n"                         // 请求头
                + "content-Length: "+ html.getBytes().length + "\r\n"
                + "\r\n"                                                // 空行
                + html ;                                                // 响应体
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write(response.getBytes());
            // outputStream.flush();
            // outputStream.close();
        }
    }
}

改进

  • Request
public class Request{
    private String requestType;
    private String url;
    // 请求协议
    private String protocolType;
    // 其他请求参数
    private Map<String,String> headers;
    // 请求体
    private String requestBody;
    
    // get set
    // toString
}
  • RequestHandler
// 解析生成request
public class RequestHandler{
    public static Request requestHandler(Socket socket) throws IOException{
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = socket.getInputStream();
        
        byte[] bytes = new byte[1024];
        int len = inputSTream.read(bytes);
        sb.append(new String(bytes,0,len));
        // 请求行请求头 请求体
        String[] headerAndBody = sb.toString().split("\r\n\r\n");
        // 请求行 请求头
        String[] split = headerAndBody[0].split("\r\n");
        // 请求类型 url 协议
        String[] typeSplit = split[0].split(" ");
        
        Request request = new Request();
        request.setRequestType(typeSplit[0]);
        request.setUrl(typeSplit[1]);
        request.setProtocolType(typeSplit[2]);
        
        Map<String,String> headers = new HashMap<>();
        for(int i=1;i<split.length();i++){
            if(split[i]==null||"".equals(split(i))){
                break;
            }
            String[] others = split[i].split(": ");
            headers.put(others[0],others[1]);
        }
        request.setHeaders(headers);
        if(headerAndBody.length==2){
            request.setRequestBody(headerAndBody[1]);
        }
        return request;
    }
}
  • Response
public class Response{
    private final String CRLF = "\r\n";
    
    private StringBuilder responseLine = new StringBuilder();
    private StringBuilder responseHeader = new StringBuilder();
    private StringBuilder responseBody = new StringBuilder();
    
    private String content;
    
    
    // 构建响应行
    private void buildResponseLine(int code){
        responseLine.append("HTTP/1.1").append(" ").append(code).append(" ");
        switch(code){
            case 404:
                responseLine.append("NOT FOUND");
                break;
            case 505:
                responseLine.append("SEVER ERROR");
                break;
            case 200:
                responseLine.append("OK");
                break
        }
        responseLine.append(CRLF);
    }
    
    // 构建响应头
    private void buildResponseHeader(String contentType){
        responseHeader.append("Content-type:").append(contentType).append(";charset=utf-8").append(CRLF);
        responseHeader.append("Content-Length:").append(content.getBytes().length()).append(CRLF);
        responseHeader.append(CRLF);
    }
    
    // 构建响应体
    private void buildResponseBody(){
        responseBody.append(content);
    }
    
    private String build(int code,String content,String contentType){
        setContent(content);
        buildResponseLine(code);
        buildResponseHeader(contentType);
        buildResponseBody();
        return responseLine.append(responseHeader).append(responseBody).toString();
    }
    
    private void setContent(String content){
        this.content = content;
    }
}
  • BootStrap
public class BootStrap{
    public static void main(String[] args){
        ServiceSocket server = new ServerSocket();
        // 监听 8888端口
        server.bind(new InetSocketAddress(8888));
        System.out.println("服务器启动:8888");
        while(true){
            Socket accept = server.accept();
            // 解析socket
            Request request = RequestHandler.requestHandler(accept);
            System.out.println(request.getUrl());
           if(request.getUrl().equals("/home")){
                String html = "<h1>home</h1>"
                String response = "http/1.1 200 ok\r\n"                     // 请求行
                    + "content-Type: text/html\r\n"                         // 请求头
                    + "content-Length: "+ html.getBytes().length + "\r\n"
                    + "\r\n"                                                // 空行
                    + html ;                                                // 响应体
                OutputStream outputStream = accept.getOutputStream();
                outputStream.write(response.getBytes());
           }else if(request.getUrl().equals("/page")){
                String html = "<h1>page</h1>"
                // response封装
                Response response = new Response();
                String str = response.build(200,html,"text/html");
                OutputStream outputStream = accept.getOutputStream();
                outputStream.write(str.getBytes());
           }else{
                // 获取本地文件 
                InputStream resourceAsStream = Bootstrap.class.getClassLoader().getResourceAsStream("/page/index.html");
                byte[] buf = new byte[1024];
                StringBuilder html = "";
                int len;
                while((len=resourceAsStream.read(buf))!=-1){
                    html.append(new String(buf,0,len));
                }
             
                // response封装
                Response response = new Response();
                String str = response.build(200,html,"text/html"); 
                OutputStream outputStream = accept.getOutputStream();
                outputStream.write(response.getBytes());
           }
            
          

        }
    }
}

改进(分发)

  • BootStrap
public class BootStrap{
    public static void main(String[] args){
        ServiceSocket server = new ServerSocket();
        // 监听 8888端口
        server.bind(new InetSocketAddress(8888));
        System.out.println("服务器启动:8888");
        
        while(true){
            Socket accept = server.accept();
            // 解析socket
            Request request = RequestHandler.requestHandler(accept);
            // 请求分发
            Response response = RequestDispatcher.dispatch(request);
          

        }
    }
}
  • RequestDispatch
public class RequestDispatch{
    public static Response dispatch(Request request){
        String url = request.getUrl();
        // url 映射对应的内容
        
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值