Today, a thing needs to use Java NIO. On the Internet to check the information, found that there is Apache Mina,netty, and so on, feel the JDK with the NIO a little chicken AH. Have seen this part of the content before, but for a long time no use, also forget 7788. Now it is warm and new, but there are some questions:
Put the code on it first:
public static void Main (string[] args) throws Exception{thread sh=new Thread (New Runnable () {public void run () {Try{servers Ocket ss=new ServerSocket (3000); Socket client=ss.accept (); OutputStream Os=client.getoutputstream (); while (true) {Os.write ("Helloworld"). GetBytes ()) ; Thread.Sleep (1000);}} catch (Exception e) {e.printstacktrace ();}}}); Sh.start (); Socketchannel Sc=socketchannel.open (); Sc.socket (). Connect (new inetsocketaddress ("localhost", 3000)); Sc.configureblocking (FALSE); Selector Selector=selector.open (); Sc.register (Selector,selectionkey.op_read); Bytebuffer bytebuffer=bytebuffer.allocate (+); while (true) {if (Selector.select () >0) {set<selectionkey> Sks=selector.selectedkeys (); for (Selectionkey key:sks) {if (key.isreadable ()) {System.out.println ("is readable ()"); Socketchannel isc= (Socketchannel) Key.channel (); Isc.read (Bytebuffer);} Sks.remove (key);}} System.out.println ("Return from Select ()");}}
About the need to sks.remove (key) this line.
Follow the results of the above operation:
is readable () return from select () are readable () return from select () is readable () return from select () is readable () RET Urn from select ()
Then comment out the Sks.remove (key) line and run it again:
is readable () return from select () return from select () return from select () the From select () return from select () retu RN from select () return from select () return from select () return from select () return from select () return from select () Return from select () return from select () ...
Illustrates that if you do not perform a remove operation in Selectedkyes for a selectionkey that has already been processed. The next select () operation will return directly, but the value returned is 0
The key set returned by Selectedkeys in JAVA NiO, after which an action is taken on Selectionkey, whether it is necessary to perform a remove operation in Selectedkeys ()