Java Socket NiO Sample Summary

Source: Internet
Author: User

Java nio non-blocking IO implementation, based on event-driven, is very suitable for the server needs to maintain a large number of connections, but the amount of data exchange is not small, such as some instant communication services, etc., it mainly consists of three parts:

    • Channels
    • Buffers
    • Selectors

The channel has two serversocketchannel and socketchannel,serversocketchannel that can listen for the newly added socket connection, Socketchannel for both read and write operations. NiO always writes the data in the buffer to the channel, or reads the data from the channel into the buffer.

Buffer is essentially a piece of memory for reading and writing, just packaged as a buffer object, you can request memory space through Allocatedirect () or allocate () (the memory overhead generated by the allocate allocation method is in the JVM, In particular, buffer needs to understand three concepts when the Allocatedirect allocation method generates overhead outside the JVM, in order to be system-level memory allocations, with allocatedirect in particular attention to memory overflow issues.

capacity, position, limit,capacity are fixed size, position is the current read and write position, and limit is a threshold-like value for controlling the maximum position of read and write. The usual methods of buffer are clear, compact, flip, and so on, such as buffer static method wrap and so on, these need according to capacity, position, limit values to understand, the above Ifeve on the article is very detailed, I will not be tired of the statement.

Selector is used to detect the channel, we know which channel is which event, so if we need to use selector, we need to register first, and then traverse the Selectionkey to handle the event. It has a total of Selectionkey.op_connect, selectionkey.op_accept, Selectionkey.op_read, selectionkey.op_write four types of events.

I'm just summarizing this here, and the concept of NiO http://ifeve.com/java-nio-all/can be seen here.

http://blog.csdn.net/ns_code/article/details/15545057 Orchid Pavilion Wind and rain This demo good, I directly copied over.

Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.channels.SelectionKey;ImportJava.nio.channels.Selector;ImportJava.nio.channels.ServerSocketChannel;ImportJava.util.Iterator; Public classNioserver {Private Static intbuff_size=1024; Private Static intTime_out = 2000;  Public Static voidMain (string[] args)throwsIOException {Selector Selector=Selector.open (); Serversocketchannel Serversocketchannel=Serversocketchannel.open (); Serversocketchannel.bind (NewInetsocketaddress (10083)); Serversocketchannel.configureblocking (false);                Serversocketchannel.register (selector, selectionkey.op_accept); Tcpprotocol Protocol=NewEchoselectorprotocol (buff_size);  while(true) {            if(Selector.select (time_out) ==0){                //while waiting for channel preparation, you can also perform other tasks asynchronously, where you print *System.out.print ("*"); Continue; } Iterator<SelectionKey> Keyiter =Selector.selectedkeys (). iterator ();  while(Keyiter.hasnext ()) {Selectionkey key=Keyiter.next (); //if the server-side channel is interested in I/O operation is accept                if(Key.isacceptable ()) {protocol.handleaccept (key); }                  //If the client channel is interested in the I/O operation as read                if(Key.isreadable ()) {protocol.handleread (key); }                  //if the key value is valid and its corresponding client channel is interested in the I/O operation is write                if(Key.isvalid () &&key.iswritable ())                  {Protocol.handlewrite (key); }                                //you need to manually remove the current key from the key set.Keyiter.remove (); }                    }    }}
Import java.io.IOException; Import Java.nio.channels.SelectionKey;  Public Interface Tcpprotocol {    voidthrows  IOException;     void throws IOException;     void throws IOException;}
Importjava.io.IOException;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SelectionKey;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.channels.SocketChannel; Public classEchoselectorprotocolImplementsTcpprotocol {Private intBufSize;//the length of the buffer     PublicEchoselectorprotocol (intbufSize) {       This. bufSize =bufSize; } @Override Public voidHandleaccept (Selectionkey key)throwsIOException {System.out.println ("Accept"); Socketchannel Socketchannel=( (Serversocketchannel) Key.channel ()). Accept (); Socketchannel.configureblocking (false);            Socketchannel.register (Key.selector (), Selectionkey.op_read, Bytebuffer.allocate (bufSize)); } @Override Public voidHandleread (Selectionkey key)throwsIOException {socketchannel Clntchan=(Socketchannel) Key.channel (); //gets the attachment associated with the channel, which is a bufferBytebuffer buf =(Bytebuffer) key.attachment ();        Buf.clear (); LongBytesread =Clntchan.read (BUF); //if the Read () method returns 1, indicating that the client has closed the connection, the client has received data that is equal to the number of bytes sent by itself and can safely close        if(Bytesread = =-1) {clntchan.close (); }Else if(Bytesread > 0){            //If the buffer is always read into the data, the operation that is of interest to the channel is set to be readable and writableKey.interestops (Selectionkey.op_read |selectionkey.op_write); }} @Override Public voidHandlewrite (Selectionkey key)throwsIOException {//TODO auto-generated Method StubBytebuffer buffer=(Bytebuffer) key.attachment ();        Buffer.flip (); Socketchannel Clntchan=(Socketchannel) Key.channel (); //writing data to the channelclntchan.write (buffer); if(!buffer.hasremaining ()) {                    //if the data in the buffer has all been written to the channel, the operation that is of interest to the channel is set to a readableKey.interestops (Selectionkey.op_read); }         //make room for reading more databuffer.compact (); }} 
Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SocketChannel; Public classnioclient { Public Static voidMain (string[] args)throwsIOException {socketchannel Clntchan=Socketchannel.open (); Clntchan.configureblocking (false); if(!clntchan.connect (NewInetsocketaddress ("localhost", 10083))){              //continuously polls the connection state until the connection is complete             while(!Clntchan.finishconnect ()) {                  //While waiting for a connection, other tasks can be performed to give full play to the asynchronous nature of non-blocking IO//here to demonstrate the use of the method, just print "."System.out.print ("."); }           }                //in order to print with the following "." Difference, here output line breaksSystem.out.print ("\ n"); //instantiate a buffer to read and write separatelyBytebuffer writebuf= Bytebuffer.wrap ("Send Send to send". GetBytes ()); Bytebuffer Readbuf= Bytebuffer.allocate ("Send". GetBytes (). length-1);  while(Writebuf.hasremaining ()) {//If there are remaining bytes in the buffer used to write data to the channel, continue to write the data to the channelClntchan.write (WRITEBUF); } stringbuffer StringBuffer=NewStringBuffer (); //if read () receives a-1, indicating that the server is closed, throws an exception             while((Clntchan.read (READBUF)) >0) {readbuf.flip (); Stringbuffer.append (NewString (Readbuf.array (), 0, Readbuf.limit ()));            Readbuf.clear (); }                //print out the received dataSystem.out.println ("Client Received:" +stringbuffer.tostring ()); //Close ChannelClntchan.close (); }}

Java Socket NiO Sample Summary

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.