Server-side:
Import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.bytebuffer;import java.nio.channels.SelectableChannel;import java.nio.channels.SelectionKey;import java.nio.channels.selector;import java.nio.channels.serversocketchannel;import java.nio.channels.socketchannel;import java.util.iterator;import java.util.linkedlist;import Java.util.list;public class serversocketthreadpool{private static final int max_ Thread = runtime.getruntime (). Availableprocessors ();p rivate threadpool pool = New threadpool (max_thread);p rivate static int port_number = 1234;public Static void main (String[] args) throws Exception {new Serversocketthreadpool (). Go (); Public void go () throws Exception {int port = PORT_NUMBER; System.out.println ("Listenning on port:" &nbsP;+ port);// Create channel ServerSocketChannelServerSocketChannel serverSocketChannel = Serversocketchannel.open ();// binds the listening port serversocketchannel.socket (). Bind (New inetsocketaddress (port)); / set to non-blocking mode serversocketchannel.configureblocking (false);// Create selector selector selector = Selector.open ();// channel registered to selector Serversocketchannel.register (selector, selectionkey.op_accept); while (true) {// blocks until there is data request Int n = selector.select ();if (n == 0) {continue;} Iterator<selectionkey> it = selector.selectedkeys (). Iterator ();while (It.hasNext ()) {selectionkey key = it.next ();if (Key.isacceptable ()) {serversocketchannel server = (Serversocketchannel) key.channel (); Socketchannel socket = server.accept (); RegisterChannel (selector,socket, selectionkey.op_ READ); SayHello (socket);} if (Key.isreadable ()) {Readdatafromsocket (key);} It.remove ();}}} Public void registerchannel (Selector selector,selectablechannel channel,int ops) Throws exception{if (channel==null) {return;} Channel.configureblocking (false); Channel.register (selector, ops);} Public void sayhello (Socketchannel socket) throws exception{bytebuffer buffer= Bytebuffer.allocate (1024x768); Buffer.clear (); Buffer.put ("Hello client". GetBytes ()); Buffer.flip (); socket.write (buffer);} Public void readdatafromsocket (Selectionkey key) throws exception {workthread thread=pool.getwork (); if (thread==null) {return;} Thread.servicechannel (key);} Private class threadpool {list idle=new linkedlist ();p Ublic threadpool (int poolsize) {for (int i=0;i<poolsize;i++) {workthread thread=new workthread (this); Thread.setname ("worker" + (i+1)); Thread.Start (); Idle.add (thread);}} Public workthread getwork () {workthread thread=null;synchronized (Idle) {if (Idle.size () >0) {thread= (workthread) idle.remove (0);}} Return thread;} Public void returnworker (Workthread workthread) {synchronized (idle) {idle.add ( Workthread);}}} private class workthread extends thread {private bytebuffer buffer = bytebuffer.allocate (1024x768);p rivate threadpool pool;private selectionkey key;public workthread (Threadpool pool) {this.pool = pool;} Public synchronized void run () {system.out.println (This.getname () + is ready ");while (True) {try {this.wait ();} catch (interruptedexception e) {e.printstacktrace (); This.interrupt ();} if (Key == null) {continue;} System.out.println (This.getname () + " has been awaken"); Try{drainchannel (key);} catch (exception e) {System.out.printlN ("caught '" "+e+" ' closing channel "); Try{key.channel (). Close (); catch (Ioexception ioe) {ioe.printstacktrace ();} Key.selector (). Wakeup ();} Key=null;this.pool.returnworker (this);}} Synchronized void servicechannel (Selectionkey key) {this.key=key;key.interestops (key.interestOps () & (~selectionkey.op_read)); This.notify ();} Void drainchannel (Selectionkey key) throws exception{socketchannel channel= (SocketChannel) key.channel (); Buffer.clear (); Int count;while ((Count=channel.read (buffer)) >0) {buffer.flip ();/* while (Buffer.hasremaining ()) {channel.write (buffer);} */byte[] bytes;bytes=new byte[count];buffer.get (bytes); System.out.println (new string (bytes)); Buffer.clear ();} if (count<0) {channel.close (); return;} Key.interestops (Key.interestops () | Selectionkey.op_read); Key.selector (). Wakeup ();}}}
Client:
import java.io.bytearrayoutputstream;import java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.bytebuffer;import java.nio.channels.selectionkey;import java.nio.channels.selector;import java.nio.channels.socketchannel;public class clienttest {private static SocketChannel socketChannel;private static Selector Selector;public clienttest () Throws exception {socketchannel=socketchannel.open (); Socketchannel.connect (new inetsocketaddress ("127.0.0.1", 1234)); Socketchannel.configureblocking ( FALSE); Selector=selector.open (); Socketchannel.register (Selector, selectionkey.op_read);} Public static void main (String[] args) throws exception{clienttest test=new clienttest (); Bytebuffer buffer=bytebuffer.allocate (1024x768); Buffer.put ("Hello server". GetBytes ()); Buffer.flip (); while (Buffer.hasremaining ()) {test.socketChannel.write (buffer);}buffer.clear (); Socketchannel.socket (). Shutdownoutput (); String response=receivedata (Test.socketchannel); SYSTEM.OUT.PRINTLN (response);} Public static string receivedata (SOCKETCHANNEL&NBSP;SOCKETCHANNEL2) throws Ioexception {bytearrayoutputstream baos = new bytearrayoutputstream (); string response = ""; try {bytebuffer buffer = bytebuffer.allocate (1024); byte[] bytes;int count = 0;while ((count = socketchannel2.read (buffer)) >= 0) {buffer.flip (); bytes = new byte[count];buffer.get (bytes); Baos.write ( bytes); Buffer.clear ();} Bytes = baos.tobytearray (); response = new string (bytes);} finally {try {baos.close ();} catch (Exception ex) {}}return response;}}
For a more detailed understanding of the thread pool of Serversocketchannel, refer to the fourth Chapter selector of the book "JAVA NIO".
This article is from the "Maple Leaf is not red" blog, please be sure to keep this source http://itlearninger.blog.51cto.com/12572641/1948807
JAVA NIO Serversocketchannel (thread pool Edition)