In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the basic knowledge of Netty learning BIO, NIO, AIO". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the basic knowledge of Netty learning BIO, NIO, AIO"!
Basic concept
The IO model means what kind of channel is used to send and receive data. Java supports changing the network into IO mode: BIO, NIO, AIO. BIO, NIO and AIO in Java are understood as the encapsulation of various IO models of the operating system by the Java language. When we use these API, we do not need knowledge at the operating system level, nor do we need to write different code according to different operating systems.
Before we talk about BIO, NIO, and AIO, we will review a few concepts: synchronous and asynchronous, blocking and non-blocking, and the Icano model.
Synchronous and asynchronous
Synchronization: synchronization means that after a call is made, the call does not return until the callee has finished processing the request.
Async: asynchronism means that after sending a call, the callee immediately receives the request, but the callee does not return a result, so other requests can be processed at this time. The callee usually relies on events, callbacks and other mechanisms to notify the caller of the returned result.
The biggest difference between synchronous and asynchronous is that the asynchronous caller does not need to wait for the result to be processed, and the callee will notify the caller to return the result through callback and other mechanisms.
Blocking and non-blocking
Blocking: blocking is the initiation of a request, and the caller is waiting for the result of the request to return, that is, the current thread will be suspended, unable to perform other tasks, and can continue only when the conditions are ready.
Non-blocking: non-blocking is to initiate a request, and instead of waiting for the result to return, the caller can do something else first.
Synchronous async and blocking non-blocking (jokes)
The story of Lao Zhang boiling water (story source network)
Lao Zhang likes to drink tea, doesn't talk nonsense, and boils boiling water.
Participants: Lao Zhang, two kettles (ordinary kettle, abbreviated kettle; ringing kettle, ringing kettle for short).
1. Lao Zhang put the kettle on the fire and waited for the water to boil. (synchronous blocking)
Lao Zhang feels a little stupid.
two。 Lao Zhang put the kettle on the fire, went to the living room to watch TV, and from time to time went to the kitchen to see if the water was boiling. (synchronous non-blocking)
Lao Zhang still felt a little stupid, so he changed to the high end and bought a kettle that could play the flute. After the water boils, it can make a loud ticking noise.
3. Lao Zhang put the ringing kettle on the fire and waited for the water to boil. (asynchronous blocking)
Lao Zhang doesn't think it makes sense to wait so foolishly.
4. Lao Zhang put the ringing kettle on the fire and went to the living room to watch TV. He stopped watching the kettle before it rang, and then went to get it. (asynchronous non-blocking)
Lao Zhang thinks he is smart.
The so-called synchronous and asynchronous, only for the kettle
Ordinary kettle: synchronous; ringing kettle: asynchronous.
Although all can work, the ringing kettle can remind Lao Zhang that the water is boiling after it is finished, which is beyond the reach of an ordinary kettle.
Synchronization only allows the caller to poll himself (in case 2), resulting in Lao Zhang's inefficiency.
The so-called blocking non-blocking, only for Lao Zhang
Lao Zhang of Li et al: blocking; Lao Zhang watching TV: non-blocking.
In case 1 and case 3, Lao Zhang was blocked, and his wife called him unaware of it. Although the ringing kettle in case 3 is asynchronous, it doesn't make much sense for Lao Zhang, who is waiting. Therefore, asynchrony is generally used in conjunction with non-blocking, so that it can play the role of asynchrony.
Comparison of common Ipaw O models
All systems are divided into two phases: waiting to be ready and operating.
For example, the read function is divided into waiting for the system to be readable and the real reading; similarly, the write function is divided into waiting for the network card to write and the real write.
It is important to note that blocking waiting for ready does not use CPU and is "waiting for nothing"; while blocking for real read operations uses CPU and is really "working", and the process is very fast, belongs to memory copy, and the bandwidth is usually above the 1GB/s level, which can be understood as basically time-consuming.
Comparison of the following common Istroke O models:
Take socket.read () as an example:
In the traditional BIO socket.read (), if there is no data in the TCP RecvBuffer, the function will block until the data is received and the read data is returned.
For NIO, if TCP RecvBuffer has data, it reads the data from the network card into memory and returns it to the user; otherwise, it returns 0 directly and never blocks.
AIO (Async I Dot O) takes it a step further: not only is waiting ready non-blocking, but even the process of data from the network card to memory is asynchronous.
In other words, BIO users are most concerned with "I want to read", NIO users are most concerned with "I can read", and in the AIO model users need to focus more on "finished".
An important feature of NIO is that the main read, write, register, and receive functions of socket are non-blocking during the wait-and-ready phase, and the real Imax O operation is synchronously blocked (consuming CPU but with very high performance).
BIO (Blocking I * O)
Synchronously blocks the Icano mode, where reads and writes to data must be blocked in a thread waiting for it to complete (a client connection for a processing thread).
Traditional BIO
The BIO communication (one request and one reply) model is shown below (figure source network):
For service queues using the BIO communication model, a separate Acceptor thread is usually responsible for listening for client connections. We usually listen to the request by calling the accept () method in the while (true) loop to wait for the client to connect. Once the request receives a connection request, we can set up a communication socket to read and write on this communication socket. At this time, we can no longer receive other client connection requests, but can only wait for the operation of the currently connected client to be completed. However, multiple client connections can be supported through multithreading, as shown in the figure above.
If you want the BIO communication model to process requests from multiple clients at the same time, you must use multithreading (because the three main functions involved in socket.accept (), socket.read (), and socket.write () are all synchronously blocking). When a connection is dealing with IWeiO, the system is blocked, and if it is a single thread, it hangs there. By turning on multithreading, you can let CPU handle more things. In other words, after receiving the client connection request, it creates a new thread for each client for link processing, and after the processing is completed, it is returned to the client through the output stream, and the thread is destroyed. This is a typical one-request-reply communication model.
In fact, this is the essence of all the use of multithreading:
Take advantage of multicore
CPU resources can be used with multithreading when the system is blocked by CPU O, but the CPU is idle.
We can imagine that the following will cause unnecessary thread overhead if the connection does nothing, but it can be improved through the thread pool mechanism, and the thread pool can also make the thread creation and recovery cost relatively low. For example, the use of FixedTreadPool can effectively control the maximum number of threads, ensure the control of the limited resources of the system, and achieve the pseudo-asynchronous Imodo O model of N (number of client requests): M (number of threads handling client requests) (N can be much larger than M).
Let's imagine what will go wrong with this model when client-side concurrent traffic increases. With the increase of concurrent access, the rapid expansion of the number of threads may lead to problems such as thread stack overflow, failure to create new threads, and eventually lead to process downtime or deadlock, unable to provide services.
Threads are valuable resources in Java virtual machines, which are mainly reflected in:
1. The cost of creating and destroying threads is very high, especially in the Linux operating system, threads are essentially a process, and creating and destroying threads are heavyweight system functions.
two。 The thread itself takes up a large amount of memory, such as the thread stack of Java, which generally allocates at least the space of 512k~1M. If the number of threads in the system exceeds 1000, I am afraid that half of the memory of the whole JVM will be eaten.
3. The switching cost of threads is also high. When a thread switch occurs in the operating system, you need to retain the context of the thread and then execute the system call. If the number of threads is too high, the thread switching time may even be longer than the thread execution time. The performance of this time is that the system load is on the high side, and the CPU sy utilization rate is particularly high (more than 20%), causing the system to almost fall into an unavailable state.
4. It is easy to cause jagged system load. Because the load of the system is the number of active threads and the number of CPU cores, once the number of threads is high but the external network environment is not very stable, it is easy to cause a large number of request results to return at the same time, activate a large number of blocking threads and make the system load too much. The high value of sy > sy in CPU in Linux system means that the kernel consumes it. If the value of sy is too high, don't consider the kernel problem first. Check whether the memory is insufficient, the disk is full, or the IO problem. That is to say, consider the problem of your own process first, such as whether it is caused by IO or network. Check whether the system IO or network has reached a bottleneck.
Pseudo async IPUP O
In order to solve the problem that synchronous blocking IAccord O needs a thread to process a link, someone later optimized its thread model: the back end handles the request access of multiple clients through a thread pool, forming a proportional relationship between the number of clients M: the maximum number of threads N in the thread pool, in which M can be much larger than N. Through the thread pool, we can flexibly allocate thread resources and set the maximum value of threads to prevent thread exhaustion due to massive concurrent access.
Pseudo-out-of-step IO model diagram (diagram source network)
Using thread pools and task queues, we can implement a pseudo-asynchronous Imax O communication framework, whose model diagram is shown in the figure above. When a new client is connected, the Socket of the client is encapsulated as a Task (the task implements the java.lang.Runnable interface) and delivered to the thread pool at the back end for processing. The thread pool of JDK maintains a message queue and N active threads to process the tasks in the message queue. Because the thread pool can set the size of the message queue and the maximum number of threads, its resource consumption is controllable, no matter how many clients access concurrently, it will not cause resource exhaustion and downtime.
The pseudo-asynchronous Iripo communication framework uses thread pool implementation, so it avoids the problem of thread resource exhaustion caused by creating a separate thread for each request. However, because its underlying layer is still a synchronous blocking BIO model, it cannot fundamentally solve the problem.
Shortcoming
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
The read operation in IO code is a blocking operation. If the connection does not read and write data, it will cause thread blocking and waste of resources.
If there are too many threads, it will result in too many server threads and too much pressure.
Application scenario
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, but the program is simple to understand.
BIO code example
Server side
Package com.niuh.bio; import java.io.IOException; import java.net.ServerSocket;import java.net.Socket;public class SocketServer {public static void main (String [] args) throws IOException {ServerSocket serverSocket = new ServerSocket (9000); while (true) {System.out.println ("waiting for connection.") ; / / blocking method final Socket socket = serverSocket.accept (); System.out.println ("client connected.") ; / / multithreaded new Thread (new Runnable () {@ Override public void run () {try {handler (socket);} catch (IOException e) {e.printStackTrace () }) .start (); / / single threading / / handler (socket);}} private static void handler (Socket socket) throws IOException {System.out.println ("thread id =" + Thread.currentThread () .getId ()); byte [] bytes = new byte [1024] System.out.println ("prepare read.") ; / / receive data from the client, blocking method, blocking int read = socket.getInputStream () .read (bytes) when there is no data to read; System.out.println ("read is over.") ; if (read! =-1) {System.out.println ("data received from the client:" + new String (bytes, 0, read)); System.out.println ("thread id =" + Thread.currentThread (). GetId ());} socket.getOutputStream (). Write ("HelloClient" .getBytes ()); socket.getOutputStream (). Flush ();}}
Client
Package com.niuh.bio; import java.io.IOException; import java.net.Socket; public class SocketClient {public static void main (String [] args) throws IOException {Socket socket = new Socket ("127.0.0.1", 9000); / / send data socket.getOutputStream (). Write ("HelloServer" .getBytes ()); socket.getOutputStream (). Flush () System.out.println ("end of sending data to server"); byte [] bytes = new byte [1024]; / / receiving data returned by server socket.getInputStream () .read (bytes); System.out.println ("receiving data from server:" + new String (bytes)); socket.close ();}}
NIO (Non Blocking IO)
Synchronous non-blocking, the server implementation mode is that a thread can handle multiple requests (connections), the connection requests sent by the client will be registered with the multiplexer selector, and the multiplexer polls that the connection has IO requests for processing.
It supports the buffer-oriented, channel-based Imap O operation method. NIO provides two different socket channel implementations of SocketChannel and ServerSocketChannel corresponding to Socket and ServerSocket in the traditional BIO model, and both channels support blocking and non-blocking modes.
Blocking mode is as simple as traditional support, but its performance and reliability are not good.
The non-blocking mode is just the opposite.
For applications with low load and low concurrency, we can use synchronous blocking I / O to improve development speed and better maintainability; for applications with high load and high concurrency, we should use NIO's non-blocking mode to develop.
NIO core components
NIO has three core components:
Channel (Channel)
Buffer (buffer)
Selector (selector)
The whole NIO system contains far more than these three classes, it can only be said that these three are the "core API" of the NIO system.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Channel is similar to a stream. Each channel corresponds to a buffer buffer, and the underlying buffer is an array.
Channel will register on selector and selector will hand it over to some idle thread to handle according to the occurrence of channel read and write events.
Selector can correspond to one or more threads
NIO's Buffer and channel can be read or written.
Characteristics of NIO
Let's sum up from a question: what is the difference between NIO and IO?
If you are answering this question in an interview, I think the first thing to start with is that the NIO stream is a non-blocking IO and the IO stream is a blocking IO. It can then be analyzed from the improvements brought to NIO by the three core components / features of NIO.
IO flow is blocked, NIO flow is not blocked
Java NIO enables us to perform non-blocking IO operations. For example, a single thread reads data from a channel to buffer while continuing to do other things, and when the data is read into the buffer, the thread continues to process the data. It's the same with writing data. In addition, non-blocking writing is also daily, a thread requests to write some data to a channel, but does not need to wait for it to be fully written, the thread can do something else at the same time.
The various streams of Java IO are blocked, which means that when a thread calls read () or write (), the thread is blocked until some data is read or completely written. The thread can no longer do anything during this time.
IO is stream oriented (Stream oriented), NIO is buffer oriented (Buffer oriented)
Buffer (buffer)
A Buffer is an object that contains data to be written or read. The addition of Buffer objects to the NIO class library reflects an important difference between the new library and the original library.
In stream-oriented iCompO, you can write data directly or read data directly into Stream objects. Although there are extension classes enabled by Buffer in Stream, they are only wrapper classes for streams and read from streams to buffers.
NIO is read directly into Buffer for operation. In the NIO library, all data is processed with buffers. When data is read, it is read directly into the buffer; when data is written, it is written to the cache. Any time you access the data in NIO, you operate through a buffer.
The most commonly used buffer is that ByteBuffer,ByteBuffer provides a stream set of functions for manipulating byte arrays. There are other buffers besides ByteBuffer, and in fact, every Java base type (except the Boolean type) has a buffer.
NIO reads and writes through Channel (channel)
Channel (Channel)
Channels are bidirectional, readable and writable, while streaming reads and writes are unidirectional. Regardless of read or write, the channel can only interact with Buffer. Because of Buffer, channels can read and write asynchronously.
NIO has a selector, while IO does not
Selectors (selector)
Selectors are used to process multiple channels using a single thread. Therefore, it requires fewer threads to process these channels. Switching between threads is expensive for the operating system. Therefore, it is useful to provide a system efficiency selector.
NIO reads and writes data
Generally speaking, all IO in NIO starts with Channel (channel).
Read data from the channel: create a buffer and then request the channel to read the data
Write data from the channel: create a buffer, populate the data, and require the channel to write data.
The data read and write operations are as follows:
Application scenario
NIO is suitable for architectures with a large number of connections and short connections (light operation), such as chat server, on-screen comment system, server-to-server communication, and complex programming.
NIO code example
Server side
Package com.niuh.nio; 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;public class NIOServer {/ / public static ExecutorService pool = Executors.newFixedThreadPool (10) Public static void main (String [] args) throws IOException {/ / create a service Socket channel that listens on the local port. And set to non-blocking mode ServerSocketChannel ssc = ServerSocketChannel.open (); / / must be configured for non-blocking to register on selector, otherwise an error will be reported. Selector mode itself is non-blocking mode ssc.configureBlocking (false); ssc.socket (). Bind (new InetSocketAddress (9000)); / / create a selector selector Selector selector = Selector.open () / / register ServerSocketChannel to selector, and selector is interested in client-side accept connection operations ssc.register (selector, SelectionKey.OP_ACCEPT); while (true) {System.out.println ("wait for the event to occur.") ; / / key,select in polling listening channel is blocked, and accept () is also blocked int select = selector.select (); System.out.println ("an event has occurred.") ; / / there is a client request, which is monitored by polling to hear Iterator it = selector.selectedKeys () .iterator (); while (it.hasNext ()) {SelectionKey key = it.next (); / / Delete the key that has been processed this time to prevent the next select from repeatedly processing it.remove () Handle (key);} private static void handle (SelectionKey key) throws IOException {if (key.isAcceptable ()) {System.out.println ("client connection event occurred.") ; ServerSocketChannel ssc = (ServerSocketChannel) key.channel (); / / NIO non-blocking reflects: here the accept method is blocked, but here because a connection event has occurred, this method will be executed immediately, and will not block / / process the connection request and will not continue to wait for the client's data to be sent SocketChannel sc = ssc.accept () Sc.configureBlocking (false); / / interested in reading events when listening to Channel via Selector sc.register (key.selector (), SelectionKey.OP_READ);} else if (key.isReadable ()) {System.out.println ("client data readable events have occurred.") ; SocketChannel sc = (SocketChannel) key.channel (); ByteBuffer buffer = ByteBuffer.allocate (1024); / / NIO non-blocking embodiment: first, the read method will not block, secondly, this event response model, when the read method is called, there must be an event int len = sc.read (buffer) that the client sends data If (len! =-1) {System.out.println ("read data sent by the client:" + new String (buffer.array (), 0, len));} ByteBuffer bufferToWrite = ByteBuffer.wrap ("HelloClient" .getBytes ()); sc.write (bufferToWrite); key.interestOps (SelectionKey.OP_READ | SelectionKey.OP_WRITE) } else if (key.isWritable ()) {SocketChannel sc = (SocketChannel) key.channel (); System.out.println ("write event") / / NIO event triggers are triggered horizontally / / when NIO programming with Java is used, write events are canceled when there is no data to write out, / / write events key.interestOps (SelectionKey.OP_READ) are registered when there is data to write out; / / sc.close ();}
Detailed analysis of NIO server program:
Create a ServerSocketChannel and Selector and register ServerSocketChannel with Selector
Selector listens for channel events through the select () method. When the client connects, selector listens to the connection event and gets the selectionKey bound to ServerSocketChannel when registering.
SelectionKey can get the bound ServerSocketChannel through the channel () method
ServerSocketChannel gets SocketChannel by accept () method.
Register SocketChannel on Selector and care about read events
Return a SelectionKey after registration, which will be associated with the SocketChannel
Selector continues to listen for events through the select () method. When the client sends data to the server, Selector listens to the read event and gets the SelectionKey bound when the SocketChannel is registered.
SelectionKey can get the bound socketChannel through the channel () method
Read out the data in socketChannel
Use socketChannel to write the server data back to the client.
Client
Package com.niuh.nio; 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.SocketChannel;import java.util.Iterator;public class NioClient {/ / Channel Manager private Selector selector / * start client test * * @ throws IOException * / public static void main (String [] args) throws IOException {NioClient client = new NioClient (); client.initClient ("127.0.0.1", 9000); client.connect () } / * get a Socket channel and do some initialization work on it * * @ param ip connected server ip * @ param port connected server port number * @ throws IOException * / public void initClient (String ip, int port) throws IOException {/ / get a Socket channel SocketChannel channel = SocketChannel.open () / / set the channel to non-blocking channel.configureBlocking (false); / / get a channel manager this.selector = Selector.open () / / the client connects to the server, but the method execution does not implement the connection. You need to call / / use channel.finishConnect () in the listen () method to complete the connection channel.connect (new InetSocketAddress (ip, port)); / / bind the channel manager to the channel and register the SelectionKey.OP_CONNECT event for the channel. Channel.register (selector, SelectionKey.OP_CONNECT);} / * uses polling to listen for events that need to be handled on the selector, and if so, handle * * @ throws IOException * / public void connect () throws IOException {/ / polling access selector while (true) {selector.select () / / get the iterator Iterator it = this.selector.selectedKeys () .iterator () of the selected item in selector; while (it.hasNext ()) {SelectionKey key = (SelectionKey) it.next (); / / delete the selected key to prevent repeated processing of it.remove () / / connection event occurs if (key.isConnectable ()) {SocketChannel channel = (SocketChannel) key.channel (); / / if you are connecting, complete the connection if (channel.isConnectionPending ()) {channel.finishConnect () } / / set to non-blocking channel.configureBlocking (false); / / you can send a message to the server here, ByteBuffer buffer = ByteBuffer.wrap ("HelloServer" .getBytes ()); channel.write (buffer) / / after a successful connection with the server, you need to set the read permission to the channel in order to receive the information from the server. Channel.register (this.selector, SelectionKey.OP_READ); / / got a readable event} else if (key.isReadable ()) {read (key) } / * handle the event of reading the information sent by the server * * @ param key * @ throws IOException * / public void read (SelectionKey key) throws IOException {/ / is the same as the server's read method / / server readable Get the message: get the Socket channel SocketChannel channel = (SocketChannel) key.channel () where the event occurred / / create read buffer ByteBuffer buffer = ByteBuffer.allocate (1024); int len = channel.read (buffer); if (len! =-1) {System.out.println ("client receives message:" + new String (buffer.array (), 0, len));}
Summary
The selector of the NIO model is like a master manager who listens for various Icano events and then transfers them to the back-end thread for processing.
The manifestation of NIO's non-blocking relative to BIO is that the back-end thread of BIO needs to block waiting for the client to write data (such as the read method), and will block if the client does not write the data thread.
NIO gives it to the master selector when the client operates. Selector is responsible for polling all registered clients and transferring it to the back-end thread for processing when it finds that an event has occurred. The back-end thread does not need to do any blocking waiting, just deal with the data of the client event directly, and finish processing immediately, or return to the thread pool for other client events to continue to use. There is also the non-blocking reading and writing of channel.
Redis is a typical NIO threading model. Selector collects all events and transfers them to the back-end thread, which continuously executes all event commands and writes the results back to the client.
AIO (Asynchronous I * O)
Asynchronous non-blocking, after the completion of the operating system, the callback informs the server program to start the thread to process, which is generally suitable for applications with a large number of connections and a long connection time.
AIO is also known as NIO 2. NIO 2, an improved version of NIO, is introduced in Java 7, which is an asynchronous non-blocking IO model. Asynchronous IO is implemented based on the event and callback mechanism, that is, it will return directly after the application operation, and will not be blocked there. When the background processing is completed, the operating system will notify the corresponding thread for subsequent operations.
AIO is an acronym for asynchronous IO. Although NIO provides a non-blocking method in network operations, the IO behavior of NIO is synchronous. For NIO, our business thread is notified when the IO operation is ready, and then the thread performs the IO operation on its own, and the IO operation itself is synchronized. (all IO types except AIO are synchronized)
Application scenario
The AIO method is suitable for architectures with a large number of connections and long connections (reoperation).
AIO code example
Server side
Package com.niuh.aio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; public class AIOServer {public static void main (String [] args) throws Exception {final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open () .bind (new InetSocketAddress (9000)) ServerChannel.accept (null, new CompletionHandler () {@ Override public void completed (final AsynchronousSocketChannel socketChannel, Object attachment) {try {/ / receive the client connection again, if you don't write this line of code, the client connection cannot connect to the server serverChannel.accept (attachment, this) System.out.println (socketChannel.getRemoteAddress ()); ByteBuffer buffer = ByteBuffer.allocate (1024); socketChannel.read (buffer, buffer, new CompletionHandler () {@ Override public void completed (Integer result, ByteBuffer buffer) {buffer.flip () System.out.println (new String (buffer.array (), 0, result)); socketChannel.write (ByteBuffer.wrap ("HelloClient" .getBytes () @ Override public void failed (Throwable exc, ByteBuffer buffer) {exc.printStackTrace ();}}) } catch (IOException e) {e.printStackTrace ();}} @ Override public void failed (Throwable exc, Object attachment) {exc.printStackTrace ();}}); Thread.sleep (Integer.MAX_VALUE);}}
Client
Package com.niuh.aio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; public class AIOClient {public static void main (String... Args) throws Exception {AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open (); socketChannel.connect (new InetSocketAddress ("127.0.0.1", 9000). Get (); socketChannel.write (ByteBuffer.wrap ("HelloServer" .getBytes ()); ByteBuffer buffer = ByteBuffer.allocate (512); Integer len = socketChannel.read (buffer). Get () If (len! =-1) {System.out.println ("client receives message:" + new String (buffer.array (), 0, len));}
Comparison of BIO, NIO and AIO
Thank you for your reading, the above is the content of "what is the basic knowledge of Netty learning BIO, NIO, AIO". After the study of this article, I believe you have a deeper understanding of what the basic knowledge of Netty learning is BIO, NIO, AIO, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.