Java socket

通信原理 img.png

通过sb压测 ./sb -u http://localhost:8801 -c 40 -N 30 单线程客户端

public class HttpServer01 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8801);
        while (true) {
            try (Socket accept = serverSocket.accept();) {
                service(accept);
            }
        }
    }

    public static void service(Socket socket) {
        try (PrintWriter printWriter = new PrintWriter(socket.getOutputStream());) {
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Type:text/html;charset=utf-8");
            String body = "hello,nio1";
            //显示告诉报文长度
            printWriter.println("Content-Length:" + body.getBytes(StandardCharsets.UTF_8).length);
            //报文头和报文体通过空行分割
            printWriter.println();
            printWriter.write(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

多线程客户端

/**
 * 多线程客户端
 */
public class HttpServer02 {
    public static void main(String[] args) throws IOException {
        ExecutorService executors = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 2);
        System.out.println(Runtime.getRuntime().availableProcessors());
        ServerSocket serverSocket = new ServerSocket(8802);
        while (true) {
            final Socket accept = serverSocket.accept();
            executors.execute(() -> service(accept));
        }
    }
    public static void service(Socket socket) {
        try (PrintWriter printWriter = new PrintWriter(socket.getOutputStream());) {
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Type:text/html;charset=utf-8");
            String body = "hello,nio2";
            //显示告诉报文长度
            printWriter.println("Content-Length:" + body.getBytes(StandardCharsets.UTF_8).length);
            //报文头和报文体通过空行分割
            printWriter.println();
            printWriter.write(body);
            printWriter.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

深入io

img_1.png

img_2.png

IO模型

同步:发起请求后等待处理结果 异步:发起请求后,接受通知或检查处理结果

同步、异步指通信模式 阻塞、非阻塞是线程的处理模式

img.png

基本都是同步模型

针对java中而言
BIO:blocking 阻塞I/O模型
NIO:non-blocking 同步非阻塞I/O模型

1.阻塞式IO

img_1.png

2.非阻塞IO

img_1.png

3.IO多路复用

img.png img.png

新增reactor和epoll 共享内存空间

4.信号驱动IO

img.png

5.异步IO

img.png

6.压测工具压测服务端

  1. sb sb -u http://localhost:8801 -c 40 -N 30