I. BIO of I/O model

BIO of I/O model

Basic introduction

  • Java BIO is the traditional Java IO programming, and its related classes and interfaces are under the java.io package
  • BIO (blocking I/O): synchronous blocking. The implementation mode of the server is to connect one thread at a time. That is, when the client has a connection request, the server needs to start a thread for processing. However, if the newly started thread does not do anything, it will cause unnecessary overhead, which can be improved through the thread pool mechanism
  • The BIO model is suitable for a fixed architecture with a small number of connections. This method requires high server resources and poor concurrency performance. It was used before JDK 1.4

The process of BIO programming

  1. Start a SeverSocket 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
  3. After the client sends out the request, first ask the server if there is a thread response. If not, it will wait or be rejected
  4. If the server responds, the client's current thread will wait for the request to end before proceeding

Application example

Example illustrate

  1. Use the BIO model to write a server and listen to port 6666. When there is a client connection, start a thread to communicate with it
  2. Improved thread pool mechanism is required to connect multiple clients
  3. The server can receive the data sent by the client (using telnet)

Instance code:

public class BIOServer {
    public static void main(String[] args) throws Exception {
        //1. Create a thread pool
        ExecutorService threadPool = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("Server started up!!!");
        while (true){
            //Listening, waiting for client connection
            final Socket socket = serverSocket.accept();
            System.out.println("Connect to a client");
            //2. If a client is connected, create a thread to communicate with (write a method separately)
            threadPool.execute(new Runnable() {
                public void run() {
                    //Communicating with clients
                    handler(socket);
                }
            });
        }

    }

    //Write a handler method to communicate with client
    public static void handler(Socket socket){
        //For receiving data
        byte[] bytes = new byte[1024];
        //Get input stream through socket
        InputStream inputStream = null;
        try {
            System.out.println("thread id="+Thread.currentThread().getId()+"Name="+Thread.currentThread().getName());
            inputStream = socket.getInputStream();

            //Loop read data sent by client
            while(true){
                int read = inputStream.read(bytes);
                if (read!=-1){
                    //Output data sent by client
                    System.out.println("Received message:+new String(bytes,0,read));
                }else{
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("Close connection to client......");
            try {
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Test results:

Server started up!!!
Connect to a client
 Thread id=12 name = pool-1-thread-1
 Message received: nihao

Tags: Java socket Programming JDK

Posted on Thu, 28 Nov 2019 13:31:50 -0800 by Gnub