Learn Java Netty (i)--Java NiO

Source: Internet
Author: User

In the recent study of the Java Netty Network framework, the first one introduced the Java NIO.
Java NiO introduced in jdk1.4, in fact, is also relatively early, the main introduction of non-blocking IO and IO multiplexing. Internal based on reactor mode.

NIO Core:
-Buffer
-Channel
-Selector

Buffer
Similar to the buffer in network programming, there are
Bytebuffer bytes
Charbuffer characters
Intbuffer
DoubleBuffer ...
Commonly used are bytebuffer and charbuffer.

Java NiO Buffer opens up a space with 4 marks inside, Position,limit,capicity,mask.

Position is the current read buffer position, limit is the end of the data, indicating the maximum read to the limit position, capacity is the capacity of the buffer, between position and limit there will be a mask to mark a position, can move position to mask position
Buffer has two important ways to clear and flip
The clear () method does not empty the data but instead position the 0,limit to capacity.
Ready to load data to buffer again
The flip () method sets the limit to the current position position after the data is loaded, and then the position is set to 0, which simply means that flip () is ready to take the data out of buffer.

>

Channel
Similar to sockets in network programming, Java NiO is called Channel, which is more convenient for us to understand that the transfer of data between the server and the client is through channel channels.
Channel has
FileChannel File Pipeline
Datagramchannel Datagram Pipeline
Socketchannel Socket Pipeline
Serversocketchannel service-side socket pipeline
Channel can map part or all of a file directly to buffer
Attention:
The program cannot directly access channel data, and the channel must be used in conjunction with buffer.
All channel should not use the constructor, from the traditional stream node InputStream and so on to obtain the channel

Selector
Event distribution collector, internal encapsulated epoll. We can register events above and then listen to events on multiple channel channels.

Timing Diagram

Note: Pictures are not original

From the timing diagram, we can see that Java NiO is much like the network programming we write.

Java NiO implements a simple loopback server
ImportJava.io.IOException;Importjava.net.InetAddress;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;Importjava.nio.channels.*;ImportJava.nio.channels.spi.SelectorProvider;ImportJava.nio.charset.Charset;ImportJava.util.Set;/** * Created by WWH on 15-7-25. * * Public  class niosocket {    encoding and decoding of//character sequences and byte sequences    PrivateCharset Charset = Charset.forname ("UTF-8");voidRun (String IP,intPortthrowsIOException {Try{//Create a service-side socketServersocketchannel Server = Serversocketchannel.open ();//Bind IP and PortsServer.socket (). Bind (NewInetsocketaddress (IP, port));//Set non-blockingServer.configureblocking (false);//Create selector event selectorSelector Selector = Selector.open ();//Register your listening sockets with the selector to monitor the Accept event            //selectionkey represents the relationship between Selectablechannel and selector, and selectable is an event channel that can be monitored by selector.Server.register (selector, selectionkey.op_accept); while(Selector.select () >0){//selector.select () return event                 for(Selectionkey Sk:selector.selectedKeys ()) {//Delete the event being processed from the event collectionSelector.selectedkeys (). Remove (SK);//Determine the type of event, and then process                    if(Sk.isacceptable ()) {//If the event is an accept connection Accpet eventSystem.out.println ("Accpet Event");//Call Accept accepts request connectionSocketchannel client = Server.accept ();//Set to non-blockingClient.configureblocking (false);//To register read events on selectorClient.register (selector, selectionkey.op_read);//Set SK corresponding channel to be ready to accept other requestsSk.interestops (selectionkey.op_accept); }if(Sk.isreadable ()) {//If the event is a readable eventSystem.out.println ("Read Event"); Socketchannel client = (Socketchannel) sk.channel ();//define buffersBytebuffer buffer = Bytebuffer.allocate (1024x768); String MESG ="";Try{ while(Client.read (buffer) >0) {Buffer.flip ();                            MESG + = charset.decode (buffer); } System.out.println ("Received:"+ MESG);                        Sk.interestops (Selectionkey.op_read); }Catch(IOException e) {//If an exception occurs, the current client connection is canceledSk.cancel ();if(Sk.channel ()! =NULL) {Sk.channel (). Close (); }                        }//Reply to the client that sent the messageClient.write (Charset.encode (MESG)); System.out.println ("Reply:"+ MESG); }                }            }        }Catch(IOException e)        {E.printstacktrace (); }    } Public Static void Main(string[] args)throwsIOException {Niosocket Server =NewNiosocket (); Server.run ("192.168.10.75",10000); }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Learn Java Netty (i)--Java NiO

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.