Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Nginx, BIO, NIO, AIO

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what is Nginx, BIO, NIO, AIO". In daily operation, I believe many people have doubts about what is Nginx, BIO, NIO and AIO. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what is Nginx, BIO, NIO, AIO"! Next, please follow the editor to study!

1. What is IO?

two。 Understand the difference between synchronous and asynchronous, blocking and non-blocking before understanding different IO

Synchronization, you can't do anything else before the completion of a task, you have to wait (equivalent to making a phone call)

Async, other operations can be performed before the completion of a task (equivalent to talking about QQ)

Blocking, which is relative to CPU, suspends the current thread and cannot do anything but wait

Non-blocking, you can perform other operations without suspending the current thread

3. What is BIO?

BIO: synchronize and block, the server implements a connection to a thread, that is, when the client has a connection request, the server needs to start a thread to process, until it is finished, this thread cannot do other operations (if it is a single thread, the file I transferred is very large? Which can, of course, be improved through the thread pool mechanism The BIO method is suitable for the architecture with a small number of connections and a fixed number of connections, which requires high server resources, and concurrency is limited to the application. JDK1.4 is the only choice before, but the program is intuitive, simple and easy to understand.

4. What is NIO?

NIO: synchronous non-blocking, the server implements one thread per connection, that is, all connection requests sent by the client are registered with the multiplexer, and the multiplexer starts a thread for processing only when the multiplexer polls that the connection has an Imax O request. NIO is suitable for architectures with a large number of connections and relatively short connections (light operation), such as chat servers, where concurrency is limited to applications, programming is more complex, and JDK1.4 begins to support it.

5. What is AIO?

AIO: asynchronous non-blocking, the server implementation mode is an effective request for a thread, and the client Imax O requests are completed by the operating system before notifying the server application to start the thread for processing. AIO is used in architectures with a large number of connections and long connections (re-operation), such as photo album servers, which fully call the operating system to participate in concurrent operations. Programming is more complex, and JDK1.7 starts to support it later. .

AIO belongs to the class implementation in the NIO package. In fact, IO is mainly divided into BIO and NIO,AIO, which are just accessories to solve the problem that IO cannot be implemented asynchronously.

In the past, few Linux systems support AIO,Windows 's IOCP is this AIO model. But today's servers generally support AIO operations.

6. What Netty?

7. The difference between BIO, NIO and AIO

BIO is blocking and NIO is non-blocking.

BIO is stream-oriented and can only read and write in one way. NIO is buffer-oriented and can read and write in both directions.

When using BIO for Socket connections, due to one-way read and write, when there is no data, the current thread will be suspended and wait will be blocked. In order to avoid affecting other connections, it is necessary to create a new thread for each connection. However, the system resources are limited, and there can not be too many new threads. Too many threads bring thread context switching, which always brings greater performance loss, so it is necessary to use NIO for BIO multiplexing. Use one thread to listen for all Socket connections and use this thread or other thread to process the connection

AIO is a non-blocking method that initiates an Icano operation asynchronously. Other operations can be done when the iPot O operation is in progress, and the operating system kernel space alerts IO that the operation has been completed (if you don't understand, you can read on)

8. Classification of IO flows

9. What is kernel space?

10. Five IO models

Note: my user space here is the application space.

10.1 blocking BIO (blocking Ibank O)

10.2. Non-blocking NIO (noblocking Iplink O)

B also fishes by the river, but B doesn't want to spend all his time fishing. During the time when waiting for the fish to take the bait, B is also doing other things (reading books, reading newspapers, reading other people's fishing, etc.). But when B is doing these things, check to see if the fish is hooked at regular intervals. Once you detect that a fish has taken the bait, stop what you are doing and catch the fish. B checking whether there are fish in the fishing rod is a polling process.

10.3. Asynchronous AIO (asynchronous Ihamo)

10.4. Signal driven IO (signal blocking Istroke O)

G also fishes by the river, but unlike A, B and C, G is smarter. He hangs a bell on the fishing rod. When a fish takes the bait, the bell will be rung and G will catch the fish.

10.5.IO Multiplex transfer (Igamot O multiplexing)

11. What is a Bit, what is a Byte, what is a character (Char), what are their lengths, and what are their differences

The smallest binary unit of Bit, with a value of 0 or 1 for the operating part of the computer

Byte is the unit in which data is stored in a computer, which is an 8-bit binary number. (inside the computer, one byte can represent an English letter and two bytes can represent a Chinese character. ) value (- 128-127)

Char is the smallest unit that a user can read or write. It is just a symbol in an abstract sense. Such as' 5years','¥', and so on. In java, the value of Char composed of 16-bit bit (0-65535)

Bit is the smallest unit of computer. He can only recognize 0 or 1.

Byte is 8 bytes. It's for the computer.

A character is what you see. One character = two bytes.

twelve。 What is object serialization, what is deserialization, and what needs to be done to implement object serialization

Object serialization, saving the object in binary form on the hard disk

Deserialization; convert binary files to object reads

Implement the serializable interface and add transient if you don't want the fields to be placed on the hard disk.

13. When you implement a serialization interface, you usually generate a serialVersionUID field. What is it called, and what is its use?

If the user does not declare a serialVersionUID by himself, the API generates a serialVersionUID by default

However, it is strongly recommended that users customize a serialVersionUID, because the default serialVersinUID is very sensitive to the details of class and may cause the exception InvalidClassException when deserialization.

(for example, if you serialize first and then modify the class before deserialization, an error will be reported. Because the class is modified, the corresponding SerialversionUID changes, and serialization and deserialization are done by comparing their SerialversionUID, and once the SerialversionUID does not match, deserialization will not succeed.

14. How to generate SerialversionUID

15. What kind of stream does BufferedReader belong to? what is it mainly used for? there are some classic methods in it.

Belongs to the buffer flow in the processing flow, and the read content can be stored in memory. There are readLine () methods.

16. What are the main superclasses of streams in Java?

The superclass represents the top parent class (all abstract classes)

Java.io.InputStream

Java.io.OutputStream

Java.io.Reader

Java.io.Writer

17. Why do pictures, videos, music, files and so on need to be read by byte stream?

18. Common classes and methods of IO, and how to use the

19. Explain the basic operation of IO

The basic operation here is the ordinary read operation. If you want to have a deep understanding of different IO development scenarios, you must first understand the basic operation of IO.

20. IO explanation of Network Operation

I use Socket to simply simulate the problems caused by network programming IO.

If you don't understand Socket, you can see my previous article. This thing is easy to understand, that is, network communication based on TCP is faster than http. Many frameworks for network communication are based on Socket.

21. Evolution History of Network Operation IO programming 21.1 what's wrong with BIO programming?

The package com.test.io;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;//TCP protocol Socket uses BIO for communication: the server public class BIOServer {/ / executes the following code in the main thread public static void main (String [] args) {/ / uses Socket for network communication ServerSocket server = null;Socket socket = null;// based on byte stream InputStream in = null;OutputStream out = null Try {server = new ServerSocket (8000); System.out.println ("server starts successfully, listening port is 8000, waiting for client connection..."); while (true) {socket = server.accept (); / / waiting for client connection System.out.println ("customer connection succeeded, customer information is:" + socket.getRemoteSocketAddress ()); in = socket.getInputStream (); byte [] buffer = new byte [1024]; int len = 0 / / read data from the client while ((len = in.read (buffer)) > 0) {System.out.println (new String (buffer, 0, len));} / / write data out = socket.getOutputStream () to the client; out.write ("hello!" .getBytes ());}} catch (IOException e) {e.printStackTrace ();}} TCP protocol Socket uses BIO for communication: client (second execution) package com.test.io;import java.io.IOException Import java.io.OutputStream;import java.net.Socket;import java.util.Scanner;//TCP protocol Socket uses BIO for communication: client public class Client01 {public static void main (String [] args) throws IOException {/ / create socket object socket and encapsulate ip and portSocket socket = new Socket ("127.0.0.1", 8000); / / get an output stream based on the created socket object / / based on byte stream OutputStream outputStream = socket.getOutputStream () / / console input is sent to server System.out.println in the form of IO ("TCP connection is successful\ nPlease enter:"); String str = new Scanner (System.in). NextLine (); byte [] car = str.getBytes (); outputStream.write (car); System.out.println ("Socket sent successfully for TCP protocol"); / / refresh buffer outputStream.flush (); / / close connection socket.close ();}} package com.test.io Import java.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.util.Scanner;//TCP protocol Socket: client public class Client02 {public static void main (String [] args) throws IOException {/ / create socket object socket and encapsulate ip and portSocket socket = new Socket ("127.0.0.1", 8000); / / get an output stream based on the created socket object / / based on byte stream OutputStream outputStream = socket.getOutputStream () / / console input is sent to the server System.out.println as IO ("TCP connection is successful\ nPlease enter:"); String str = new Scanner (System.in). NextLine (); byte [] car = str.getBytes (); outputStream.write (car); System.out.println ("Socket sent successfully for TCP protocol"); / / refresh buffer outputStream.flush (); / / close connection socket.close ();}}

To solve the congestion problem, you can use multithreading, as shown below

21.2 Multithreading to solve the problems in BIO programming

At this point, some people will say, I am not multi-threaded to solve it?

The problem of long waiting time can be solved by using multithreading, because it can make full use of CPU.

However, the system resources are limited, and there can not be too many new threads. Too many threads bring thread context switching, which always brings greater performance loss.

Package com.test.io;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;//TCP protocol Socket uses multithreaded BIO for traffic: server public class BIOThreadService {public static void main (String [] args) {try {ServerSocket server = new ServerSocket (8000); System.out.println ("server starts successfully, listening port is 8000, waiting for client connection.") While (true) {Socket socket = server.accept (); / wait for the customer to connect to System.out.println ("customer connection succeeded, customer information is:" + socket.getRemoteSocketAddress ()); / / create a thread for each connection to handle the I0 operation / / create multithreaded creation start Thread thread = new Thread (new Runnable () {try {InputStream in = socket.getInputStream (); byte [] buffer = new byte [1024]; int len = 0 / / read the client's data while ((len = in.read (buffer)) > 0) {System.out.println (new String (buffer, 0, len));} / / write data OutputStream out = socket.getOutputStream () to the client; out.write ("hello" .getBytes ());} catch (IOException e) {e.printStackTrace ();}); thread.start ();}} catch (IOException e) {e.printStackTrace ();}

In order to solve the problem of too many threads, here comes again, thread pool

21.3 Thread Pool to solve the problems in multithreaded BIO programming

Package com.test.io;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors / / TCP protocol Socket uses thread pool BIO for traffic: server public class BIOThreadPoolService {public static void main (String [] args) {/ / create thread pool ExecutorService executorService = Executors.newFixedThreadPool (30); try {ServerSocket server = new ServerSocket (8000) System.out.println ("server starts successfully, listening port is 8000, waiting for client connection..."); while (true) {Socket socket = server.accept () / / wait for the customer to connect to System.out.println ("customer connection is successful, customer information is:" + socket.getRemoteSocketAddress ()) / / use threads in the thread pool to execute each corresponding task executorService.execute (new Thread (new Runnable () {public void run () {try {) InputStream in = socket.getInputStream () Byte [] buffer = new byte [1024]; int len = 0 / / read the client's data while ((len = in.read (buffer)) > 0) {System.out.println (new String (buffer, 0, len)) } / / write data to the client OutputStream out = socket.getOutputStream () Out.write ("hello" .getBytes ());} catch (IOException e) {e.printStackTrace () })) }} catch (IOException e) {e.printStackTrace ();} 21.4 use NIO to realize network communication

Package com.test.io;import com.lijie.iob.RequestHandler;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.util.Iterator;import java.util.Set Public class NIOServer {public static void main (String [] args) throws IOException {/ / 111111111 / / Channel on the service side, ServerSocketChannel serverChannel = ServerSocketChannel.open () of the listening port; / / set to non-blocking serverChannel.configureBlocking (false) / / nio's api specifies that the port serverChannel.bind (new InetSocketAddress (8000)) is assigned in this way; / / shows whether the Channel has been started successfully, including the address at which the System.out.println is bound ("the server starts successfully, and the listening port is 8000, waiting for the client to connect." + serverChannel.getLocalAddress ()) / / 22222222 / / declare the selector selector Selector selector = Selector.open (); / / the meaning of this sentence is to register selector with Channel, / / after each client comes, register the client with the Selector selector. The default state is Accepted serverChannel.register (selector, SelectionKey.OP_ACCEPT). / / 33333333 / / create a buffer buffer with a declared size of 1024, and the underlying ByteBuffer buffer = ByteBuffer.allocate (1024) using an array; RequestHandler requestHandler = new RequestHandler () / / 444444444 / / polling, the server constantly polls, waiting for the client connection / / if there is a client polling, take out the corresponding Channel, and keep polling while (true) {int select = selector.select () If (select = = 0) {continue;} / / there may be many, use Set to save Channel Set selectionKeys = selector.selectedKeys (); Iterator iterator = selectionKeys.iterator () While (iterator.hasNext ()) {/ / use SelectionKey to get Channel SelectionKey key = iterator.next () that connects the client and the server. / / determine the status of Channel in SelectionKey If it is OP_ACCEPT, enter if (key.isAcceptable ()) {/ / extract Channel ServerSocketChannel channel = (ServerSocketChannel) key.channel () from the judgment SelectionKey. / / get the Channel SocketChannel clientChannel = channel.accept () of the corresponding client / / print out the client Channel System.out.println ("client channel information print:" + clientChannel.getRemoteAddress ()) / / set the Channel of the client to non-blocking clientChannel.configureBlocking (false); / / change the status of the Channel in the SelectionKey OP_READ clientChannel.register (selector, SelectionKey.OP_READ) } / / when I arrived at this round of training, I found that my status was read. Start data exchange if (key.isReadable ()) {/ / use buffer as data bridge SocketChannel channel = (SocketChannel) key.channel () / / if you want to read and write data, you must first read it into buffer and manipulate channel.read (buffer). / / read String request = new String (buffer.array ()) .trim (); buffer.clear () / / print the data System.out.println in buffer (String.format ("message from client:% s:% s", channel.getRemoteAddress (), request)) / / if you want to return data, you must first return to buffer and return String response = requestHandler.handle (request). / / then return channel.write (ByteBuffer.wrap (response.getBytes ();} iterator.remove ();}}

Package com.test.io;import java.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.util.Scanner;//TCP protocol Socket: client public class Client01 {public static void main (String [] args) throws IOException {/ / create socket object socket and encapsulate ip and port Socket socket = new Socket ("127.0.0.1", 8000) / / get an output stream OutputStream outputStream = socket.getOutputStream () based on the created socket object; / / the console input is sent to the server System.out.println in the form of IO ("TCP connection is successful n Please enter:") While (true) {byte [] car = new Scanner (System.in). NextLine (). GetBytes (); outputStream.write (car); System.out.println ("Socket sent successfully for TCP protocol") / / refresh buffer outputStream.flush ();} 21.5 use Netty to realize network communication

Netty is an open source Java framework provided by JBOSS. Netty provides asynchronous, event-driven network application framework and tools for the rapid development of high-performance, high-reliability network servers and client programs.

Netty is a client-server programming framework based on NIO. Using Netty can ensure that you can quickly and easily develop a network application, such as a client-server application that implements a certain protocol. Netty simplifies and streamlines the programming and development process of network applications, such as Socket service development for TCP and UDP.

At this point, the study of "what is Nginx, BIO, NIO, AIO" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report