计算机网络:Socket编程-面向对象封装

上篇写的 计算机网络:Socket编程-实现HTTP服务 来进行面向对象封装

1、代码实现

package com.hh.http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.function.Function;

/**
 * 面向对象封装
 *
 * @author hang.yuan 2022/3/8 18:30
 */
public class HttpServer2 {

    ServerSocket serverSocket;

    Function<String,String> handler;

    public HttpServer2(Function<String, String> handler) {
        this.handler = handler;
    }

    public void listen(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        while (true){
           this.accept();
        }
    }

    public void accept() {
        try{
            // Blocking ...
            // Thread --> Sleep --> Other Threads
            Socket socket = serverSocket.accept();
            System.out.println("socket created");

            InputStream inputStream = new DataInputStream(socket.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder requestBuilder = new StringBuilder();

            String line = "";

            while (true){
                line = bufferedReader.readLine();
                if(line ==null || line.isEmpty()){
                    break;
                }
                requestBuilder.append(line+"\n");
            }
            String request = requestBuilder.toString();
            System.out.println(request);

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String response = this.handler.apply(request);
            bufferedWriter.write(response);
            bufferedWriter.flush();
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        HttpServer2 server = new HttpServer2( req -> {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "HTTP/1.1 201 ok\n\nGood!\n";
        });

        server.listen(8000);

    }
}

2、测试

  • 测性能工具 ab
测性能工具 ab 测性能工具功能 ab
  • 开始测试 开始测试

  • 结果 结果

  • 使用更大的并发测试,发现Pending Queue被占满,直接拒绝请求了 被占满,直接拒绝请求