Java sockets, Socketserver, read and write, connection event monitoring, are all blocking-type. Java provides another non-blocking read-write, connection event listening mode--nio. This article briefly introduces a NIO socket primer example, principles and detailed usage, referring to subsequent articles
Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SelectionKey;ImportJava.nio.channels.Selector;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.channels.SocketChannel;ImportJava.util.Iterator;/*** * NIO Socket Server *@authorCoshaho*/ Public classnioserver{ Public Static voidMain (string[] args)throwsIOException {//start the socket Server ChannelServersocketchannel Server =Serversocketchannel.open (); Server.bind (NewInetsocketaddress (8001)); Server.configureblocking (false); //binding selector, registering connection listener eventsSelector Selector =Selector.open (); Server.register (selector, selectionkey.op_accept); Selectorhandler Handler=NewSelectorhandler (); while(true) { //non-blocking listener registration Events if(Selector.select (2000) = = 0) {System.out.println ("No Selection"); Continue; } //Discover registration events, processing in turnIterator<selectionkey> Keyiter =Selector.selectedkeys (). iterator (); while(Keyiter.hasnext ()) {Selectionkey key=Keyiter.next (); if(Key.isacceptable ()) {handler.doaccept (key); } if(Key.isreadable ()) {handler.doread (key); } if(Key.isvalid () &&key.iswritable ()) {Handler.dowrite (key); } keyiter.remove (); } } } /*** Event handler *@authorh00219638*/ Public Static classSelectorhandler {//connection Request Processing Public voidDoaccept (Selectionkey key)throwsIOException {socketchannel socket=( (Serversocketchannel) Key.channel ()). Accept (); Socket.configureblocking (false); //registering data Read EventsSocket.register (Key.selector (), Selectionkey.op_read, Bytebuffer.allocate (1024)); } Public voidDoread (Selectionkey key)throwsIOException {socketchannel socket=(Socketchannel) Key.channel (); //You can also temporarily assign BytebufferBytebuffer buf =(Bytebuffer) key.attachment (); Buf.clear (); if(-1 = =Socket.read (BUF)) {Socket.close (); } Else{System.out.println ("Server Received:" +NewString (Buf.array (), 0, Buf.limit ())); /*** public static final int op_read = 1 << 0; public static final int op_write = 1 << 2; public static final int op_connect = 1 << 3; public static final int op_accept = 1 << 4; */ //increase write events, write events will continue to be triggered, after the data has been written must be canceled write event monitoringKey.interestops (Key.interestops () |selectionkey.op_write); } } Public voidDowrite (Selectionkey key)throwsIOException {socketchannel socket=(Socketchannel) Key.channel (); Bytebuffer buf=(Bytebuffer) key.attachment (); //Note Call the Flip method before writing the data, reset the pointerBuf.flip (); System.out.println ("Write:" +NewString (Buf.array (), 0, Buf.limit ())); Socket.write (BUF); if(!buf.hasremaining ()) { //Cancel Write Event listenerKey.interestops (Key.interestops () &~selectionkey.op_write); } buf.compact (); } } }
Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SocketChannel;Importorg.drools.core.util.StringUtils;/*** * NIO Socket Client *@authorCoshaho*/ Public classnioclient{ Public Static voidMain (string[] args)throwsIOException {socketchannel socket=Socketchannel.open (); Socket.configureblocking (false); if(!socket.connect (NewInetsocketaddress ("localhost", 8001)) {System.out.println ("Not Connect"); //is really connected while(!Socket.finishconnect ()) {System.out.println ("Not Finishconnect"); }} bytebuffer wbuf= Bytebuffer.wrap ("Hello, Server". GetBytes ()); while(Wbuf.hasremaining ()) {socket.write (WBUF); } bytebuffer RBuf= Bytebuffer.allocate (8); StringBuffer Sbuf=NewStringBuffer (); while(-1! =(Socket.read (RBUF))) {Rbuf.flip (); String s=NewString (Rbuf.array (), 0, Rbuf.limit ()); Sbuf.append (s); Rbuf.clear (); if(Stringutils.isempty (s)) { Break; }} System.out.println ("Client Received:" +sbuf.tostring ()); Socket.close (); }}
Getting Started with Java Socket NiO