Random talk about the NIO of Java IO

Source: Internet
Author: User

The use of basic IO and the simplest example of blocking the server are described in the previous article, and this article introduces the relevant content of the following NIO, which you can refer to in the previous share:

    1. Basic knowledge and concepts of network IO
    2. General IO and Bio server
    3. Use of NiO with server Hello World
    4. Netty Getting Started with server Hello World
    5. Netty in Layman's

NIO, also known as New-io or Non-blocking-io, is understood as non-blocking IO for the moment.

Why Choose NiO

So what are the advantages of nio relative to Io? To summarize, say:

    1. IO is stream-oriented, and data can only be read from one end to the other and not read and written. NIO is a buffer-oriented, the operation of the data is more convenient
    2. Io is blocking, wasting server performance and increasing the risk of the server, while NiO is non-blocking.
    3. NIO introduces an IO multiplexer, which is more efficient.
What does NiO have?

So what does NiO offer?

    1. Buffer-based bidirectional pipeline, channel and buffer
    2. IO multiplexer Selector
    3. More user-friendly APIs

Use of buffer

Various buffer types are available in NiO, the most common being bytebuffer:

As you can see, they all have several more important variables:

    • capacity--capacity, this value is determined at the beginning of the application. The size of the array similar to the C language application.
    • limit--remaining, the initial time in write mode equals capacity; In read mode, it is equal to the location of the last write
    • mark--tag bit, mark the position of position, you can call the Reset () method to return to this position.
    • posistion--position, in write mode, where to start writing, and where to start reading in read mode

In summary, the NIO buffer has two modes, read mode and write mode. Just come up to write mode, use Flip () to switch to read mode.

For the use of these locations, you can refer to the following code:

 Public classbytebuffertest { Public Static void Main(string[] args) {Bytebuffer buffer = Bytebuffer.Allocate( the); System. out.println(buffer); String value ="Netty authoritative guide"; Buffer.put(value.)getBytes()); System. out.println(buffer); Buffer.Flip(); System. out.println(buffer);byte[] v =New byte[Buffer.remaining()]; Buffer.Get(v); System. out.println(buffer); System. out.println(NewString (v)); }}

The resulting output is:

java.nio.HeapByteBuffer[pos=0 lim=88 cap=88]java.nio.HeapByteBuffer[pos=17 lim=88 cap=88]java.nio.HeapByteBuffer[pos=0 lim=17 cap=88]java.nio.HeapByteBuffer[pos=17 lim=17 cap=88]Netty权威指南

Readers can take a look at what these variables mean. It is also explained that if you encounter your own definition of the Pojo class, you can overload the ToString () method with buffer like here, so the output is convenient.

Finally, for the use of Bytebuffer in the channel, you can refer to the following code:

 Public classbuffertest { Public Static void Main(string[] args)throwsIOException {String file ="Xxxx/test.txt"; Randomaccessfile Accessfile =NewRandomaccessfile (file,"RW"); FileChannel FileChannel = Accessfile.Getchannel();//20 bytesBytebuffer buffer = Bytebuffer.Allocate( -);intBytesread = FileChannel.Read(buffer);///Buffer.put () can also be written to buffer         while(bytesread!=-1){//write switch to readBuffer.Flip(); while(buffer.hasremaining()) {System. out.println((Char) buffer.Get()); }//Buffer.rewind () re-read            //Buffer.mark () Mark position buffer.reset () recovery            //Clear bufferBuffer.Clear();//Buffer.compact (); Clearly read the dataBytesread = FileChannel.Read(buffer); }    }}

In this way, we are familiar with the use of channel and Bytebuffer. Next, look at the application in the server.

NiO Server Example

In front of the bio server, it is a connection to create a new thread response. This is based on the multiplexing of NIO, which can be written like this:

Import Java.io.ioexception;import Java.net.inetsocketaddress;import Java.net.serversocket;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 Plainnioserver {public void serve (int port) throws IOException {//Create channel and bind listener        Port Serversocketchannel Serversocketchannel = Serversocketchannel.open ();        Serversocketchannel.configureblocking (FALSE);        ServerSocket ssocket = Serversocketchannel.socket ();        Inetsocketaddress address = new inetsocketaddress (port);        Ssocket.bind (address);        Create the Selector and register the channel to Selector Selector Selector = Selector.open ();        Serversocketchannel.register (selector, selectionkey.op_accept);        Final Bytebuffer msg = bytebuffer.wrap ("hi\r\b". GetBytes ()); for (;;) {try{Selector.select();                }catch (IOException e) {e.printstacktrace ();            Break            } set<selectionkey> Readykeys = Selector.selectedkeys ();            iterator<selectionkey> Iterator = Readykeys.iterator ();                while (Iterator.hasnext ()) {Selectionkey key = Iterator.next ();                Iterator.remove (); try{if (key.isacceptable ()) {Serversocketchannel Server = (Serversocketchannel) k                        Ey.channel ();                        Socketchannel client= server.accept ();                        Client.configureblocking (FALSE); Client.register (Selector, Selectionkey.op_write |                        Selectionkey.op_read, Msg.duplicate ());                    SYSTEM.OUT.PRINTLN ("Accepted connection from" +client);                      } if (Key.iswritable ()) {Socketchannel client = (Socketchannel) key.channel ();  Bytebuffer buffer = (bytebuffer) key.attachment ();                           while (Buffer.hasremaining ()) {if (client.write (buffer) ==0) {break;                    }} client.close ();                    }}catch (IOException e) {key.cancel ();                    try{Key.channel (). Close ();                    } catch (IOException ex) {ex.printstacktrace (); }}}}} public static void Main (string[] args) throws IOException {Plainn        Ioserver Server = new Plainnioserver ();    Server.serve (5555); }}

This is the following step in the abstract:

    1. Create Serversocketchannel and bind ports
    2. Create a selector multiplexer and register the Channel
    3. Cyclic monitoring whether there is an event of interest occurring selector.select ();
    4. Get the handle to the event and handle it

Where selector can listen to multiple IO processing at a time, the efficiency is much higher.

Random talk about the NIO of Java IO

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.