NIO:
A simple nioserver. Enter http: // localhost: 1234 in the browser. You can see the HTTP request.
Public class test <t> implements callable <t> {private selector; // create a global selectorpublic test () throws ioexception {selector = selector. open (); serversocketchannel = serversocketchannel. open (); serversocketchannel. configureblocking (false); serversocketchannel. socket (). BIND (New inetsocketaddress (1234); serversocketchannel. register (selector, selectionkey. op_accept);} public t call () throws exception {for (;) {If (selector. select (1000) = 0) {continue;} iterator <selectionkey> keyiterator = selector. selectedkeys (). iterator (); While (keyiterator. hasnext () {selectionkey key = keyiterator. next (); If (key. isacceptable () {socketchannel clientchannel = (serversocketchannel) Key. channel ()). accept (); clientchannel. configureblocking (false); clientchannel. register (key. selector (), selectionkey. op_read);} If (key. isreadable () {// gets the socketchannel clientchannel = (socketchannel) key that communicates with the client. channel (); // obtain and reset the primary index value of the buffer bytebuffer buffer = (bytebuffer) Key. attachment (); buffer. clear (); // The number of bytes read from the read data. Long bytesread = clientchannel. read (buffer); If (bytesread =-1) {// clientchannel where no content is read. close ();} else {// prepare the buffer as the buffer in which data is transmitted. flip (); // returns the byte string (decoded using charset) string receivedstring = charset. forname ("UTF-8 "). newdecoder (). decode (buffer ). tostring (); // The console prints out system. out. println ("received information:" + receivedstring); // The text string sendstring = "Hello, client. you have received your message "+ receivedstring; // encode the string to be sent (using charset encoding) and then Package Buffer = bytebuffer. wrap (sendstring. getbytes ("UTF-8"); // send it back to clientchannel. write (buffer); // set to prepare the key for the next read or write. interestops (selectionkey. op_read | selectionkey. op_write) ;}} keyiterator. remove () ;}} public static void main (string ARGs []) throws ioexception, exception {new test (). call ();}}
Reactor mode:
1. The reactor is responsible for responding to Io events. Once an event occurs, the broadcast is sent to the corresponding handler for processing.
2. handler is responsible for non-blocking activities.
Public class reactor implements runnable {final selector; Final serversocketchannel serversocket; executorservice pool = executors. newfixedthreadpool (3); Public Reactor (INT port) throws ioexception {selector = selector. open (); serversocket = serversocketchannel. open (); inetsocketaddress address = new inetsocketaddress (port); serversocket. socket (). BIND (Address); serversocket. configureblocking (false ); // Register the channelselectionkey Sk = serversocket with the selector. register (selector, selectionkey. op_accept); // use the attache function of SK to bind an acceptor. If something happens, the acceptorsk is triggered. attach (New Acceptor ();} void dispatch (selectionkey K) {runnable r = (runnable) (K. attachment (); R. run ();} public void run () {try {While (true) {int temp = selector. select (); iterator <selectionkey> keyiter = selector. selectedkeys (). iterator (); While (keyiter. h Asnext () {selectionkey key = keyiter. next (); keyiter. remove (); dispatch (key) ;}} catch (ioexception e) {e. printstacktrace () ;}} class acceptor implements runnable {public void run () {try {socketchannel c = serversocket. accept (); If (C! = Null1_pool.exe cute (New socketreadhandler (selector, C);} catch (ioexception e) {e. printstacktrace () ;}} public static void main (string ARGs []) throws ioexception {new reactor (1234 ). run ();}}
Public class socketreadhandler implements runnable {public static logger = logger. getlogger ("socketreadhandler"); Final socketchannel SC; Final selectionkey SK; bytebuffer input = bytebuffer. allocate (1024); bytebuffer output = bytebuffer. allocate (1024); static final int reading = 0, sending = 1; int state = reading; Public socketreadhandler (selector Sel, socketchannel SC) throws ioexception {This. s C = SC; SC. configureblocking (false); SK = SC. register (SEL, 0); // when the selectionkey is bound to this handler and an event is triggered next, the run method of this class is called. // See dispatch (selectionkey K) SK. Attach (this); // mark selectionkey as readable for reading. SK. interestops (selectionkey. op_read); SEL. wakeup ();} public void run () {try {If (State = READING) {read ();} else if (State = Sending) {send () ;}} catch (ioexception e) {e. printstacktrace () ;}} private void send () throws ioexception {SC. write (output); SK. cancel ();} private void read () throws ioexception {long bytesread = SC. read (input); If (bytesread =-1) {SC. close ();} else {input. flip (); string receivedstring = charset. forname ("UTF-8 "). newdecoder (). decode (input ). tostring (); // The console prints out system. out. println ("received information:" + receivedstring); State = Sending; SK. interestops (selectionkey. op_write );}}}
The above code is adapted from reactor mode and NiO. For more information, see references.
The attach function of socketchannel links hanlder with the channel that may have events. when an event occurs, handler of the corresponding link can be triggered immediately. Added a thread pool.
Reator of Mina:
Unlike the traditional single reactor mode, Mina adopts the multiple reactor mode. Niosocketacceptor and nioprocessor use different selector to fully extract server performance.
Acctptor is mainly responsible
1. Bind one or more ports to start listening
2. process the client's chain creation request
3. disable one or more listening ports
Processor is mainly responsible
1. Accept the data sent by the client and forward it to the business logic for processing
2. send data to the client
Mina reactor Mode For details see mina1.0.10 source code: http://mina.apache.org/dyn/closer.cgi/mina/1.0.10/mina-1.0.10.zip
References:
Uniseraph: http://uniseraph.iteye.com/blog/228221--?mina=#mina的reactormode (1)"
Uniseraph: http://uniseraph.iteye.com/blog/229130--?mina=#mina的reactormode (2)"
He Yang: http://www.blogjava.net/heyang/archive/2011/01/03/342193.html--#java
Simple NiO server implementation example
Banqiao: http://www.jdon.com/concurrent/reactor.htm--w.reactorpattern and nio》