Java NiO non-blocking theory learning

Source: Internet
Author: User
Tags readable

The difference between Java NiO and blocking IO:

Blocking I/O is blocked when the Inputstream.read () method is called, and it waits until the data arrives (or times out), and similarly, when the Serversocket.accept () method is called, it is blocked until a client connection is returned. After each client connects, the server initiates a thread to process the client's request.

Disadvantages of blocking I/O:

    1. 1. When the client is a long time, a large number of processing threads are created. And each thread consumes stack space and some CPU time
      2. Blocking can lead to trivial context switching, and most context switches may be meaningless.
    2. Java NiO is used in jdk1.4, which can be said to be "new I/O", or non-blocking I/O. Here's how Java NIO works:
      1. All IO events are handled by a dedicated thread and are responsible for distribution.
      2. Event-driven: events are triggered when they arrive, rather than synchronized to monitor events.
      3. Thread communication: The threads communicate through wait,notify and other means. Ensure that each context switch is meaningful. Reduce the unnecessary process switching.

Take code as an example:

Service-side code

 PackageCn.nio;Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SelectionKey;ImportJava.nio.channels.Selector;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.channels.SocketChannel;ImportJava.util.Iterator;/*** NIO Service side *@authorPath*/ Public classNioserver {//Channel Manager    PrivateSelector Selector; /*** Get a serversocket channel and do some initialization work on the channel *@paramPort number bound by port *@throwsIOException*/     Public voidInitserver (intPortthrowsIOException {//get a serversocket channelServersocketchannel Serverchannel =Serversocketchannel.open (); //set channel to non-blockingServerchannel.configureblocking (false); //bind the ServerSocket of the channel to port portsServerchannel.socket (). Bind (Newinetsocketaddress (port)); //get a channel manager         This. selector =Selector.open (); //binds the channel manager and the channel, and registers the Selectionkey.op_accept event for that channel, after registering the event,//when the event arrives, Selector.select () returns and blocks if the event does not reach Selector.select (). Serverchannel.register (selector, selectionkey.op_accept); }    /*** Polling is used to listen for events that need to be handled on selector, and if so, to process *@throwsIOException*/@SuppressWarnings ("Unchecked")     Public voidListen ()throwsIOException {System.out.println ("The service side started successfully!" "); //Polling Access Selector         while(true) {            //when the registered event arrives, the method returns; otherwise, the method will always blockSelector.select (); //gets the iterator for the selected item in the selector, the selected item is the registered eventIterator ite = This. Selector.selectedkeys (). iterator ();  while(Ite.hasnext ()) {Selectionkey key=(Selectionkey) ite.next (); //Remove the selected key to prevent duplicate processingIte.remove (); //Client Request Connection Event                if(Key.isacceptable ()) {Serversocketchannel Server=(Serversocketchannel) key. Channel (); //get the channel to connect with the clientSocketchannel channel =server.accept (); //set as non-blockingChannel.configureblocking (false); //Here you can send a message to the client .Channel.write (Bytebuffer.wrap (NewString ("a message was sent to the client"). GetBytes ())); //after the connection with the client is successful, you need to set read permissions to the channel in order to receive the client's information. Channel.register ( This. Selector, selectionkey.op_read); //A readable event is obtained}Else if(Key.isreadable ()) {read (key); }            }        }    }    /*** Handling events that read messages sent by clients *@paramKey *@throwsIOException*/     Public voidRead (Selectionkey key)throwsioexception{//Server readable message: Gets the socket channel where the event occurredSocketchannel channel =(Socketchannel) Key.channel (); //Create a read bufferBytebuffer buffer = bytebuffer.allocate (10);        Channel.read (buffer); byte[] data =Buffer.array (); String msg=NewString (data). Trim (); System.out.println ("The server received the message:" +msg); Bytebuffer Outbuffer=Bytebuffer.wrap (Msg.getbytes ()); Channel.write (outbuffer);//to send a message back to the client    }        /*** Start the service-side test *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {nioserver server=NewNioserver (); Server.initserver (8000);    Server.listen (); }}

Client code:

 PackageCn.nio;Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SelectionKey;ImportJava.nio.channels.Selector;ImportJava.nio.channels.SocketChannel;ImportJava.util.Iterator;/*** NIO Client *@authorPath*/ Public classnioclient {//Channel Manager    PrivateSelector Selector; /*** Get a socket channel and do some initialization work on the channel *@paramIP of the IP-connected server *@paramPort number of the server to which the port is connected *@throwsIOException*/     Public voidInitclient (String IP,intPortthrowsIOException {//get a socket channelSocketchannel channel =Socketchannel.open (); //set channel to non-blockingChannel.configureblocking (false); //get a channel manager         This. selector =Selector.open (); //The client connects to the server, in fact the method execution does not implement the connection, need in the Listen () method to tune//use Channel.finishconnect () to complete the connectionChannel.connect (Newinetsocketaddress (Ip,port)); //binds the channel manager and the channel, and registers the Selectionkey.op_connect event for that channel, after registering the event,//when the event arrives, Selector.select () returns and blocks if the event does not reach Selector.select (). Channel.register (selector, selectionkey.op_connect); }    /*** Polling is used to listen for events that need to be handled on selector, and if so, to process *@throwsIOException*/@SuppressWarnings ("Unchecked")     Public voidListen ()throwsIOException {//Polling Access Selector         while(true) {            //Select a group of events that can perform I/O operations, placed in selector, which blocksSelector.select (); //gets the iterator for the selected item in the selectorIterator ite = This. Selector.selectedkeys (). iterator ();  while(Ite.hasnext ()) {Selectionkey key=(Selectionkey) ite.next (); //Remove the selected key to prevent duplicate processingIte.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 as non-blockingChannel.configureblocking (false); //here, you can send messages to the server.Channel.write (Bytebuffer.wrap (NewString ("Send a message to the server")). GetBytes ())); //after the connection with the server is successful, in order to receive the information from the server, you need to set the Read permission to the channel. Channel.register ( This. Selector, selectionkey.op_read); //A readable event is obtained}Else if(Key.isreadable ()) {read (key); }            }        }    }    /*** Handling events that read information sent from the service side *@paramKey *@throwsIOException*/     Public voidRead (Selectionkey key)throwsioexception{//same as the Read method on the service side    }            /*** Start the client Test *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {nioclient client=Newnioclient (); Client.initclient ("LocalHost", 8000);    Client.listen (); }}

Java NiO non-blocking theory learning

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.