The concept will not be said.
For a lot of NIO's open source framework, I used Mina in two projects, mainly processing data codec. This piece is done, the network part is finished mostly.
Now write network programming, no longer use the framework, directly using the Java NIO API written, fast, easy, flexible, free.
Of course, if the concept of NIO is not familiar with, or use the framework to quickly, otherwise there will be unexpected problems.
The main point that Java NiO needs to pay attention to.
First, set up network monitoring
1 intPort = 8080;2Serverchannel =Serversocketchannel.open ();3ServerSocket =Serverchannel.socket ();4selector =Selector.open ();5Serversocket.bind (Newinetsocketaddress (port));6Logger.info ("Start Server Listener for Port:" +port);7Serverchannel.configureblocking (false);8Serverchannel.register (selector, selectionkey.op_accept);
Then polling the key to process the Select
1 while(running) {2 Try{3 Selector.select ();4Iterator ite =Selector.selectedkeys (). iterator ();5 while(Ite.hasnext ()) {6Selectionkey key =(Selectionkey) Ite.next ();7 Ite.remove ();8 Acceptandreaddata (key);9 }Ten } One Catch(Throwable t) { ALogger.error ("Accept connect or read data fail", T); - } -}
Methods for handling keys
1 Public voidAcceptandreaddata (selectionkey key)2 throwsIOException, closedchannelexception {3Socketchannel channel =NULL;4 //determine the type of Operation5 if(Key.isacceptable ()) {6 //Accept client Connections7Serversocketchannel Serverchannel =(Serversocketchannel) Key.channel ();8Channel =serverchannel.accept ();9Channel.configureblocking (false);TenSelectionkey Channelkey = Channel.register (selector, Selectionkey.op_read |selectionkey.op_write); One return; A } - -Channel =(Socketchannel) Key.channel (); the //read data, and determine network status - Try { - if(Key.isreadable ()) { -Logger.debug ("---------channel is reading!------------"); +}Else if(Key.iswritable ()) { -Logger.debug ("---------channel is writing!------------"); + } A Catch(Exception e) { at Key.cancel (); - Channel.close - return; - } -}
Service-side completion, you need to note that the Select mode body is single-threaded, all the time-consuming processing can not be put into this thread.
Introduction to Java NIO Network programming Services Chapter