Java NiO socket non-blocking mode

Source: Internet
Author: User

NIO has a main class selector. This is similar to an observer. As long as we tell the selector about the socketchannel to be explored, we will continue to do other things. When an event occurs, it will notify us, return a group of selectionkeys. When we read these keys, we will obtain the socketchannel we just registered. Then, we will read data from this channel, so we can rest assured that the package will be able to read, then we can process the data.
The internal principle of selector is actually to make a round-robin access to the registered channel and continuously round-robin (this algorithm currently). Once a channel is registered, for example, when the data comes, he will stand up and report, hand over a key, and let us read the contents of this channel through this key.
The non-blocking I/O (NIO) provided by JDK effectively solves the thread overhead problem of the multi-thread server, but the usage is slightly more complicated. Multithreading is used in NIO. The main purpose is not to allocate independent service threads to respond to each client request, but to fully utilize the processing capability of multiple CPUs and the waiting time in processing through multithreading, to improve service capabilities.

Server code:

Public class helloworldserver {static int block = 1024; static string name = ""; protected selector; protected bytebuffer clientbuffer = bytebuffer. allocate (Block); protected charsetdecoder decoder; static charsetencoder encoder = charset. forname ("gb2312 "). newencoder (); Public helloworldserver (INT port) throws ioexception {selector = This. getselector (port); charset = charset. forn Ame ("gb2312"); decoder = charset. newdecoder ();} // obtain selector protected selector getselector (INT port) throws ioexception {serversocketchannel Server = serversocketchannel. open (); selector sel = selector. open (); server. socket (). BIND (New inetsocketaddress (port); server. configureblocking (false); server. register (SEL, selectionkey. op_accept); Return sel;} // listener Port Public void listen () {try {( ;) {Selector. select (); iterator iter = selector. selectedkeys (). iterator (); While (ITER. hasnext () {selectionkey key = (selectionkey) ITER. next (); ITER. remove (); process (key) ;}} catch (ioexception e) {e. printstacktrace () ;}}// process event protected void process (selectionkey key) throws ioexception {If (key. isacceptable () {// receives the serversocketchannel Server Request = (serversocketchannel) Key. channel (); Socketchannel channel = server. accept (); // you can specify a non-blocking channel. configureblocking (false); channel. register (selector, selectionkey. op_read);} else if (key. isreadable () {// read information socketchannel channel = (socketchannel) Key. channel (); int COUNT = channel. read (clientbuffer); If (count> 0) {clientbuffer. flip (); charbuffer = decoder. decode (clientbuffer); name = charbuffer. tostring (); // syst Em. out. println (name); selectionkey skey = channel. register (selector, selectionkey. op_write); skey. attach (name);} else {channel. close ();} clientbuffer. clear ();} else if (key. iswritable () {// write event socketchannel channel = (socketchannel) Key. channel (); string name = (string) Key. attachment (); bytebuffer block = encoder. encode (charbuffer. wrap ("Hello! "+ Name); channel. write (Block); // channel. close () ;}} public static void main (string [] ARGs) {int Port = 8888; try {helloworldserver Server = new helloworldserver (port); system. out. println ("listening on" + port); server. listen ();} catch (ioexception e) {e. printstacktrace ();}}}

Client code:

Public class helloworldclient {static int size = 10; static inetsocketaddress IP = new inetsocketaddress ("localhost", 8888); static charsetencoder encoder = charset. forname ("gb2312 "). newencoder (); static class message implements runnable {protected string name; string MSG = ""; public message (string index) {This. name = index;} public void run () {try {long start = system. currenttimemillis (); // open the socket channel socketchannel client = socketchannel. open (); // set to non-blocking mode client. configureblocking (false); // open the selector = selector. open (); // register the socket Action client to connect to the server. register (selector, selectionkey. op_connect); // connect to the client. connect (IP); // allocate memory bytebuffer buffer = bytebuffer. allocate (8*1024); int Total = 0; _ for: For (;) {selector. select (); iterator iter = selector. selectedkeys (). iterator (); While (ITER. hasnext () {selectionkey key = (selectionkey) ITER. next (); ITER. remove (); If (key. isconnectable () {socketchannel channel = (socketchannel) Key. channel (); If (channel. isconnectionpending () channel. finishconnect (); channel. write (encoder. encode (charbuffer. wrap (name); channel. register (selector, selectionkey. op_read);} else if (key. isreadable () {socketchannel channel = (socketchannel) Key. channel (); int COUNT = channel. read (buffer); If (count> 0) {total + = count; buffer. flip (); While (buffer. remaining ()> 0) {byte B = buffer. get (); MSG + = (char) B;} buffer. clear ();} else {client. close (); break _ For; }}} double last = (system. currenttimemillis ()-Start) * 1.0/1000; system. out. println (MSG + "used time:" + last + "s. "); MSG =" ";} catch (ioexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) throws ioexception {string Names [] = new string [size]; for (INT Index = 0; index <size; index ++) {Names [Index] = "Jeff [" + index + "]"; new thread (New message (Names [Index]). start ();}}}

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.