Chapter 2 Java BIO Programming

I / O model

Basic description of I / O model

  1. A simple understanding of the I / O model : what channel is used to send and receive data greatly determines the performance of program communication

  2. Java supports 3 network programming models / IO modes:BIO, NIO, AIO

  3. Java BIO: Synchronous and blocking (traditional blocking type) . The server implementation mode is to connect one thread , that is, the server needs to start a thread for processing when the client has a connection request. If this connection does nothing, it will cause unnecessary thread overhead.
    Insert picture description here

  4. Java NIO: Synchronous non-blocking , the server implementation mode is to process multiple requests (connections) in one thread , that is, the connection request sent by the client will be registered to the multiplexer, and the multiplexer polls for I / O requests connected Deal with
    Insert picture description here

  5. Java AIO (NIO.2) : Asynchronous and non-blocking, AIO introduces the concept of asynchronous channel, adopts Proactor mode, simplifies program writing, and starts threads only after effective requests. It is characterized by the operating system before informing the server program to start threads to process, generally Suitable for applications with many connections and long connection times

Analysis of applicable scenarios of BIO, NIO, AIO

  1. The BIO method is suitable for a relatively small and fixed number of connections . This method requires relatively high server resources, and concurrency is limited to applications. The only option before JDK 1.4, but the program is simple and easy to understand.

  2. The NIO method is suitable for architectures with a large number of connections and short connections (light operation) , such as chat servers, barrage systems, and communication between servers. Programming is more complicated, JDK1.4 began to support

  3. The AIO method is used in architectures with a large number of connections and a long connection (heavy operation) , such as an album server, which fully calls the OS to participate in concurrent operations. Programming is more complicated, and JDK7 began to support

Basic introduction to Java BIO

  1. Java BIO is traditional java io programming, and its related classes and interfaces are in java.io

  2. BIO (blocking I / O): Synchronous blocking, the server implementation mode is a connection to a thread , that is, the server needs to start a thread to process when the client has a connection request, if the connection does not do anything, it will cause unnecessary threads The overhead can be improved by the thread pool mechanism (implementing multiple clients to connect to the server). [There are application examples later]

  3. The BIO method is suitable for a relatively small and fixed number of connections . This method has relatively high requirements on server resources, and concurrency is limited to applications. The only option before JDK1.4 is simple and easy to understand

Java BIO working mechanism

Insert picture description here
Sort out the BIO programming process

  1. Start a ServerSocket on the server side
  2. The client starts Socket to communicate with the server. By default, the server needs to establish a thread for each client to communicate with it
  3. After the client sends a request, first ask the server whether there is a thread response, if not, it will wait or be rejected
  4. If there is a response, the client thread will wait for the request to end, and then continue to execute

Java BIO application examples

Example description:

  1. Use the BIO model to write a server that listens on port 6666. When a client connects, it starts a thread to communicate with it.
  2. Need to use thread pool mechanism to improve, can connect multiple clients.
  3. The server can receive the data sent by the client (telnet mode is enough).
  4. Code demo
public class BIOServer {
    public static void main(String[] args) throws Exception {

        //线程池机制

        //思路
        //1. 创建一个线程池
        //2. 如果有客户端连接,就创建一个线程,与之通讯(单独写一个方法)
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("服务器启动了");
        while (true) {

            System.out.println("线程信息 id =" + Thread.currentThread().getId() + " 名字=" + Thread.currentThread().getName());

            //监听,等待客户端连接
            System.out.println("等待连接....");
            final Socket socket = serverSocket.accept();//阻塞的,等待客户端连接,连接了就启动线程处理它
            System.out.println("连接到一个客户端");

            //就创建一个线程,与之通讯(单独写一个方法)
            newCachedThreadPool.execute(new Runnable() {
                public void run() { //我们重写
                    //可以和客户端通讯
                    handler(socket);
                }
            });
        }
    }

    //编写一个handler方法,和客户端通讯
    public static void handler(Socket socket) {

        try {
            System.out.println("线程信息 id =" + Thread.currentThread().getId() + " 名字=" + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            //通过socket 获取输入流
            InputStream inputStream = socket.getInputStream();
            //循环的读取客户端发送的数据
            while (true) {

                System.out.println("线程信息 id =" + Thread.currentThread().getId() + " 名字=" + Thread.currentThread().getName());

                System.out.println("read....");
               int read =  inputStream.read(bytes);//阻塞的,等到客户端的输入,如果没有就阻塞在这里了
               if(read != -1) {
                   System.out.println(new String(bytes, 0, read)); //输出客户端发送的数据
               } else {
                   break;
               }
            }

            System.out.println("客户端退出....");//当客户端断开发生

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭和client的连接");
            try {
                socket.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Insert picture description here
Insert picture description here

Java BIO problem analysis

  1. Each request needs to create an independent thread for data read, business processing, and data write with the corresponding client.

  2. When the number of concurrency is large, a large number of threads need to be created to handle the connection , which consumes a large amount of system resources.

  3. After the connection is established, if the current thread temporarily has no data to read, the thread is blocked on the Read operation, causing thread resource waste.

Published 138 original articles · praised 3 · visits 7236

Guess you like

Origin blog.csdn.net/weixin_43719015/article/details/105126982