The following code is only compatible with Java version 7 and above, for some key places please see the note description.
public class:
Package Com.stevex.app.nio;import Java.nio.bytebuffer;import Java.nio.charbuffer;import Java.nio.charset.charactercodingexception;import Java.nio.charset.charset;import Java.nio.charset.CharsetDecoder Import Java.nio.charset.charsetencoder;public class Charsethelper {private static final String utf_8 = "UTF-8";p rivate s Tatic Charsetencoder encoder = charset.forname (utf_8). Newencoder ();p rivate static Charsetdecoder decoder = Charset.forname (utf_8). Newdecoder ();p ublic static Bytebuffer encode (Charbuffer in) throws charactercodingexception{ Return Encoder.encode (in);} public static Charbuffer decode (Bytebuffer in) throws Charactercodingexception{return Decoder.decode (in);}}
Server code:
Package com.stevex.app.nio;import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.bytebuffer;import java.nio.charbuffer;import java.nio.channels.closedchannelexception ;import java.nio.channels.selectionkey;import java.nio.channels.selector;import java.nio.channels.serversocketchannel;import java.nio.channels.socketchannel;import java.util.iterator;public class xiaona {private bytebuffer readbuffer;private Selector selector;public static void main (String[] args) {XiaoNa xiaona = new xiaona (); Xiaona.init (); Xiaona.listen ();} Private void init () {readbuffer = bytebuffer.allocate (1024); Serversocketchannel servsocketchannel;try {servsocketchannel = serversocketchannel.open (); Servsocketchannel.configureblocking (false);//Bind Port Servsocketchannel.socket (). Bind (New inetsocketaddress ( 8383)); SELECTOR =&NBSp Selector.open (); Servsocketchannel.register (selector, selectionkey.op_accept);} catch (ioexception e) {e.printstacktrace ();}} Private void listen () {while (True) {Try{selector.select ();iterator ite = Selector.selectedkeys (). iterator (); while (Ite.hasnext ()) {selectionkey key = (Selectionkey) Ite.next (); Ite.remove ();//Ensure that the Handlekey (key) is not processed repeatedly;}} catch (throwable t) {t.printstacktrace ();}}} Private void handlekey (Selectionkey key) throws ioexception, closedchannelexception {socketchannel channel = null;try{if (Key.isacceptable ()) {serversocketchannel serverchannel = (Serversocketchannel) key.channel (); Channel = serverchannel.accept () ;//Accept connection request channel.configureblocking (false); Channel.register (Selector, selectionkey.op_read);} Else if (Key.isreadable ()) {channel = (Socketchannel) key.channel (); ReadBuffer.clear ();/* When the client channel is closed, itThe Read event is constantly received, but there is no message that the Read method returns -1 * so the server side also needs to close the channel to avoid infinite invalid processing */int count = Channel.read (Readbuffer); if (count > 0) {//must call the flip function, otherwise read the error data Readbuffer.flip ();/* Using Charbuffer mates to remove the correct data string question = new string (Readbuffer.array ()); may be an error, Readbuffer.array () returns the contents of the entire buffer because the front readbuffer.clear () does not really clean up the data but only resets the position, limit, mark of the buffer. The Decode method takes only readbuffer position to the limit data. For example, the last time the buffer was read "where", after clear position for 0,limit 1024, read again "Bye" to the buffer, position is 3,limit unchanged, flip position is 0, Limit is 3, the first three characters are overwritten, but "re" also exists in the buffer, so new string (Readbuffer.array ()) returns "Byere", while Decode ( Readbuffer) returns "Bye". */charbuffer charbuffer = charsethelper.decode (readbuffer); string question = charbuffer.tostring (); string answer = getanswer (question); Channel.write ( Charsethelper.encode (Charbuffer.wrap (answer)));} else{//The channel is closed here because the client has closed the channel or is abnormally channel.close ();}} catch (Throwable t) {t.printstacktrace (); if (channel != null) {Channel.close ()}}} Private string getanswer (string question) {String answer = null;switch (question) { case "who":answer = "I'm Cortana \";break;case "What":answer = "I'm here to help you with your sorrows"; break;case "where":answer = "I come from outer space \ \";break;case "Hi":answer = "hello\n";break;case "Bye":answer = "88\n";break;default:answer = "Please enter who, or what, or where";} Return answer;}}
Client code:
Package com.stevex.app.nio;import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.bytebuffer;import java.nio.charbuffer;import java.nio.channels.selectionkey;import java.nio.channels.Selector;import java.nio.channels.SocketChannel;import java.util.Iterator; import java.util.random;import java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.blockingqueue;import java.util.concurrent.timeunit;public class client implements Runnable{private BlockingQueue<String> words;private Random Random;public static void main (String[] args) {//multiple threads initiate a socket client connection request for (int i=0 ; i<10; i++) {client c = new client (); C.init (); New thread (c). Start ();}} @Overridepublic void run () {SocketChannel channel = null; selector selector = null;try {channel = socketchannel.open (); channel.configureblocking (false);//Request Connection Channel.connect (New inetsocketaddress (" localhost ", 8383)); Selector = selector.open (); Channel.register (selector, selectionkey.op_ CONNECT); Boolean isover = false;while (! isover) {selector.select (); iterator ite = selector.selectedkeys (). iterator (); while (Ite.hasnext ()) {selectionkey key = (Selectionkey) ite.next (); Ite.remove (); if (Key.isconnectable ()) {if (channel.isconnectionpending ()) {if ( Channel.finishconnect ()) {//Op_read event Key.interestops (Selectionkey.op_read) can only be registered if the connection is successful; Channel.write ( Charsethelper.encode (Charbuffer.wrap (Getword ())); Sleep ();} Else{key.cancel ();}}} Else if (Key.isreadable ()) {bytebuffer bytebuffer = bytebuffer.allocate (+); Channel.read ( Bytebuffer); Bytebuffer.flip (); Charbuffer charbuffer = charsethelper.decode (Bytebuffer); String answer = charbuffer.tostring (); system.out.println (ThRead.currentthread (). GetId () + "---" + answer); String word = getword (); if (word != null) {Channel.write (Charsethelper.encode ( Charbuffer.wrap (word)));} Else{isover = true;} Sleep ();}}} catch (ioexception e) {e.printstacktrace ();} Finally{if (channel != null) {try {channel.close ();} catch (ioexception e) {e.printstacktrace ();}} if (selector != null) {try {selector.close ();} catch (ioexception e) {e.printstacktrace ();}}} Private void init () {words = new ArrayBlockingQueue<String> (5); try { Words.put ("Hi"), Words.put ("who"), Words.put ("What"), Words.put ("where"); Words.put ("Bye");} catch (interruptedexception e) {e.printstacktrace ();} Random = new random ();} Private string getword () {Return words.poll ();} Private void sleep () {try {timeunit.seconds.sleep (RANdom.nextint (3));} catch (interruptedexception e) {e.printstacktrace ();}} Private void sleep (long l) {try {timeunit.seconds.sleep (l);} catch (interruptedexception e) {e.printstacktrace ();}}
This article is from "Power from absolute love!" "Blog, be sure to keep this provenance http://stevex.blog.51cto.com/4300375/1581376
JAVA NIO Server and client implementation examples