2, java BIO programming

Posted by nitediver on Wed, 26 Jan 2022 22:00:11 +0100

2.1 I/O model

  1. Simple understanding of I/O model; What channel is used to send and receive data, which largely determines the performance of program communication

  2. Java supports three network programming models I/O modes: BIO, NIO and AIO

  3. Java BIO: synchronous and blocking (traditional blocking type). The server implementation mode is one connection and one thread, that is, when the client has a connection request, the server needs to start a thread process for processing. If the connection does not do anything, it will cause unnecessary thread overhead

  4. Java NIO is synchronous and non blocking. The server implementation mode is that one thread processes multiple requests (connections), that is, the connection requests sent by the client will be registered on the multiplexer, and the multiplexer will process when it polls that there are I/O requests connected

  1. Java AIO (NIO 2) is asynchronous and non blocking. AIO introduces the concept of asynchronous channel and adopts Proactor mode. It simplifies the programming, and only effective requests can start the thread. Its feature is that the operating system notifies the server program to start the thread for processing after it is completed. It is generally suitable for applications with a large number of connections and a long connection time

2.2 applicable scenarios of BIO, NIO and AIO

  1. BIO mode is applicable to the architecture with small and fixed number of connections. This mode has high requirements for server resources, and concurrency is limited to applications. Jdk1 4 the only choice before, but the program is simple and easy to understand
  2. NIO mode is applicable to the architecture with a large number of connections and relatively short connections (light operation), such as chat server, bullet screen system, inter server communication, etc. Programming is complicated, jdk1 4 start support.
  3. AIO mode is used in architectures with a large number of connections and long connections (re operation), such as photo album server. It fully calls the OS to participate in concurrent operations. The programming is complex, and JDK7 starts to support it.

2.3 basic introduction to Java BIO

  1. Java BIO is the 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 one connection and one thread, that is, when the client has a connection request, the server needs to start a thread for processing. If the connection does not do anything, it will cause unnecessary thread overhead, which can be improved through the thread pool mechanism,
  3. BIO mode is applicable to the architecture with small and fixed number of connections. This mode has high requirements for server resources, and concurrency is limited to applications. Jdk1 4 the only choice in the past, the program is simple and easy to understand,

2.4. Working mechanism of Java BIO

Sorting out the BIO programming process

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

2.5. Java BIO application example

PS:

  1. Write a server side using BIO model, listen to port 6666, and start a thread to communicate with it when there is a client connection.
  2. It is required to improve the thread pool mechanism, which can connect multiple clients.
  3. The server can receive the data sent by the client (telnet mode is enough)
package com.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {

    public static void main(String[] args) throws IOException {
        //Thread pool mechanism
        //thinking
        //1. Create a thread pool
        //2. If there is a client connection, create a thread to communicate with it
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("Server startup");
        while(true){
            //Listen and wait for the client; connect
            final Socket socket= serverSocket.accept();
            System.out.println("Connect to a client");
            //Create a thread and communicate with it (write a separate method)
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //Can communicate with clients
                    handler(socket);
                }
            });

        }

    }

    //Write a handler method to communicate with the client
    public static void handler(Socket socket){
        try {
            byte[] bytes = new byte[1024];
            //Get the input stream through socket
            InputStream inputStream = socket.getInputStream();
            //Cyclic reading of data sent by the client
            while (true){
                int read = inputStream.read(bytes);
                if (read!=1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("Close and client Connection of");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Topics: Netty