Content: This is a simple server-client model that leverages NIO's selector to handle multiple pipelines. As for selector's introduction, look here.
Nioserver:
public class Nioserver {public static void main (string[] args) throws IOException, interruptedexception {Selector Selector = Selector.open (); Serversocketchannel Serversocketchannel = Serversocketchannel.open (); Inetsocketaddress address = new Inetsocketaddress (Inetaddress.getlocalhost (), 8080); Serversocketchannel.socket (). bind (address); Serversocketchannel.configureblocking (false); Serversocketchannel.register (selector, selectionkey.op_accept); while (true) {if (Selector.select () > 0) {set<selectionkey> selectionkeys = Selector.selectedkeys (); Iterator <SelectionKey> it = Selectionkeys.iterator (); while (It.hasnext ()) {Selectionkey Selectionkey = It.next (); if ( Selectionkey.isacceptable ()) {Serversocketchannel = (Serversocketchannel) selectionkey.channel (); Socketchannel Socketchannel = serversocketchannel.accept (); socketchannel.configureblocking (false); Socketchannel.register (selector, selectionkey.op_read); System.out.println ("Connected:" + socketchannel.socket (). GetremotesocketaDdress ());} else if (selectionkey.isreadable ()) {Socketchannel Socketchannel = (socketchannel) selectionkey.channel (); Bytebuffer buffer = bytebuffer.allocate (1024x768), while (Socketchannel.read (buffer) > 0) {buffer.flip (); byte[] dis = new b Yte[buffer.limit ()]; Buffer.get (DIS); System.out.println (new String (DIS));}} It.remove ();}} Thread.Sleep (100);}}
Nioclient:
public class Nioclient {public static void main (string[] args) throws IOException {Socketchannel Socketchannel = Socketcha Nnel.open (); inetsocketaddress address = new Inetsocketaddress (Inetaddress.getlocalhost (), 8080); Socketchannel.socket (). connect (address); SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Bytebuffer buffer = bytebuffer.allocate (1024x768); while (true) {try {buffer.clear (); String time = Sdf.format (new Date ()), Buffer.put (Time.getbytes ()); Buffer.flip (); socketchannel.write (buffer); Thread.Sleep (5000);} catch (Exception e) {System.out.println ("Connection Close");
Processing server-client model using NIO's selector