Java NIO Summary

Source: Internet
Author: User

Java NIO API Detailed

Http://www.blogjava.net/19851985lili/articles/93524.html

This article is all about the API of NIO, which helps to hold NIO on the macro level.

The BIO way makes the whole process and the connection is bound, as long as the connection is established, regardless of whether the client has the message to send, all have to wait for processing, to some extent waste the server side of the hardware resources, so there is NiO way. Java support for NIO methods is achieved through channel and Selector methods, the method used is to register an event of interest to the channel, and then through the Selector to obtain the key that occurred, such as the corresponding event occurred, the corresponding processing, Otherwise, there is no processing, is a typical reactor mode, in such a way, without the same as the BIO method, even in the absence of messages need to occupy a thread to block read messages, thereby enhancing the efficiency of the server, in order to achieve the Tcp/ip+nio mode of communication between the system, Java provides two key classes for Socketchannel and Serversocketchannel, and network IO operations are implemented by Bytebuffer, and the specific way to implement Tcp/ip+nio communication based on Java is shown below.

Server side:

Package Com.flyoung;
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.util.Iterator;
Import Java.util.Set;

Import Java.nio.channels.SocketChannel;
    public class Nioserver {/* flag number/private static int flag = 0;
    /* Define buffer size * * private static int block = 4096;
    /* Receive buffer */private static Bytebuffer Receivebuffer = Bytebuffer.allocate (block);
    /* Send buffer */private static Bytebuffer Sendbuffer = Bytebuffer.allocate (block);
    
    /* Define selector*/private Selector Selector; public nioserver (int port) throws ioexception{//Open server socket channel Serversocketchannel Serversocketchannel = Serv
        Ersocketchannel.open ();
        The server is configured to be non-blocking serversocketchannel.configureblocking (false); Retrieves the socket ServerSocket serversocket = server associated with this server socket channelSocketchannel.socket ();
        The binding Serversocket.bind for the service (new Inetsocketaddress (port));
        Find Selector selector = Selector.open () by the Open () method;
        Register to selector Serversocketchannel.register (selector, selectionkey.op_accept);
    System.out.println ("Server Start-----8888:"); //Listen for public void listen () throws ioexception{while (true) {//monitor all registered channel when registered IO operations are available
            To proceed, the function returns, and the corresponding Selectionkey is added to the Selected-key set Selector.select (); Selected-key set represents all channel monitored through the Select () method for IO operations, and this collection can be obtained by Selectedkeys () SET<SELECTIONKEY&G T
            Selectionkeys = Selector.selectedkeys ();
            Iterator<selectionkey> iterator = Selectionkeys.iterator ();
                while (Iterator.hasnext ()) {Selectionkey Selectionkey = Iterator.next ();
                Handlekey (Selectionkey);
            Iterator.remove (); }}//ProcessRequest public void Handlekey (Selectionkey selectionkey) throws ioexception{//Accept Request Serversocketchannel Ser
        Versocketchannel = null;
        Socketchannel socketchannel = null;
        String Receivetext;
        String SendText;
        int count;  Test the channel for this key is ready to accept the new socket connection if (selectionkey.isacceptable ()) {//return the channel Serversocketchannel to create this key
            (Serversocketchannel) Selectionkey.channel ();
            Accept the client's request to establish a connection and return the Socketchannel object socketchannel = Serversocketchannel.accept ();
            Configured as Non-blocking socketchannel.configureblocking (false);
        Register to selector Socketchannel.register (selector, selectionkey.op_read); }else if (selectionkey.isreadable ()) {//returns the channel for which this key was created Socketchannel = (Socketchannel) Selectionkey.cha
            Nnel ();
            Empty the buffer for the next read receivebuffer.clear (); Reads the sent data to the buffer count = Socketchannel.read (ReceiveBuffer);
                if (count>0) {receivetext = new String (Receivebuffer.array (), 0,count);
                SYSTEM.OUT.PRINTLN ("Server-side received data---" +receivetext);
            Socketchannel.register (selector, selectionkey.op_write);  
            }else if (selectionkey.iswritable ()) {//empty buffer for next write to Sendbuffer.clear ();  
            Returns the channel for which this key was created.  
            Socketchannel = (Socketchannel) selectionkey.channel ();  
            sendtext= "Message from server--" + flag++;  
             Enter data into the buffer Sendbuffer.put (sendtext.getbytes ());  
            Reset the buffer for each sign, because the data marker is changed to the inside. To read data from the server, you need to reset Sendbuffer.flip ();  
            Output to channel socketchannel.write (Sendbuffer);  
            SYSTEM.OUT.PRINTLN ("server-side sending data to the client--" +sendtext);  
        Socketchannel.register (selector, selectionkey.op_read); }} public static void Main (string[] args) throWS IOException {int port = 8888;
        Nioserver Server = new Nioserver (port);
    Server.listen (); }

}

Client

Package Com.flyoung;
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.Set;  
    public class Nioclient {/* identity number */private static int flag = 0;  
    /* Buffer size */private static int block = 4096;  
    /* Accept Data Buffer * * * private static Bytebuffer Sendbuffer = Bytebuffer.allocate (block);  
    /* Send data buffer * * private static Bytebuffer Receivebuffer = Bytebuffer.allocate (block);  /* Server-side Address * * Private final static inetsocketaddress server_address = new Inetsocketaddress ("localhost",  
  
    8888); public static void Main (string[] args) throws IOException {//Open socket channel Socketchannel Clientchannel  
        = Socketchannel.open ();  
        Set to Non-blocking mode clientchannel.configureblocking (FALSE);  
      Open selector Selector Selector = Selector.open ();  Register Connection Service Socket action Clientchannel.register (selector, selectionkey.op_connect);  
    
        Connecting Clientchannel.connect (server_address);
        Socketchannel Socketchannel;    
        Set<selectionkey> Selectionkeys;  
        String Receivetext;  
        String SendText;  
  
        int count=0;  
            while (true) {//Select a set of keys whose corresponding channels are ready for I/O operations.  
            Monitor all registered channel, when a registered IO operation can be performed, the function returns, and the corresponding Selectionkey is added to the Selected-key set Selector.select ();  
            Returns the selected set of keys for this selector.  
            Selectionkeys = Selector.selectedkeys ();  
            System.out.println (Selectionkeys.size ()); for (Selectionkey Selectionkey:selectionkeys) {//To determine if the event for the connection is established (selectionkey.isconnectab  
                    Le ()) {System.out.println ("client Connect");  Socketchannel = (Socketchannel) selectionkey.channel ();  
Determines whether a connection operation is in progress on this channel.                    Completes the socket channel connection process. if (socketchannel.isconnectionpending ()) {//Completion of connection establishment (TCP three handshake) Socketchann  
                        El.finishconnect ();  
                        SYSTEM.OUT.PRINTLN ("Complete connection!");  
                        Sendbuffer.clear ();  
                        Sendbuffer.put ("Hello,server". GetBytes ());  
                        Sendbuffer.flip ();  
                    Socketchannel.write (Sendbuffer);  
                } socketchannel.register (selector, selectionkey.op_read);  
                    else if (selectionkey.isreadable ()) {Socketchannel = (Socketchannel) selectionkey.channel ();  
                    Empty the buffer for the next read receivebuffer.clear ();  
                    Read the data sent from the server into the buffer count=socketchannel.read (receivebuffer); if (count>0) {receivetext = new String (receivebuffEr.array (), 0,count);  
                        SYSTEM.OUT.PRINTLN ("Client accepts server-side data-:" +receivetext);  
                    Socketchannel.register (selector, selectionkey.op_write);  
                    } else if (Selectionkey.iswritable ()) {sendbuffer.clear ();  
                    Socketchannel = (Socketchannel) selectionkey.channel ();  
                    SendText = "Message from client--" + (flag++);  
                     Sendbuffer.put (Sendtext.getbytes ());  
                    Reset the buffer for each sign, because the data marker is changed to the inside. To read data from the server, you need to reset Sendbuffer.flip ();  
                    Socketchannel.write (Sendbuffer);  
                    SYSTEM.OUT.PRINTLN ("client sends data to server-side-:" +sendtext);  
                Socketchannel.register (selector, selectionkey.op_read);  
        } selectionkeys.clear (); }  
    }  
}

Summary: Before the selector registration event and Socketchannel a little confused. The socketchannel is like a water pipe, when the monitor hears writes the event, writes the data to the pipeline, when hears the reading event, reads the data from the pipeline.

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.