D.bio connector vs. NIO connector two

Source: Internet
Author: User

in Tomcat, we explained two channels, bio and NIO, and here we are going through both ends of the program, simple simulation of two channels, look for similarities and differences:

BIO:
1.public class Socketserver {public socketserver () {try {int clientcount = 0;//total number of statistics clients Boolean listening = true; Whether to listen to the client ServerSocket server = NULL;      Server-Side Socket object try {//Create a serversocket on port 2121 to listen for client requests server = new ServerSocket (2121);     System.out.println ("Server starts ...");     } catch (Exception e) {System.out.println ("Can not listen to." + E);      } while (listening) {//Client count clientcount++; Listens to a customer request, creates a service thread based on the resulting socket object and customer count, and starts the New Serverthread (Server.accept (), Clientcount). Start (); = = "A request, a thread, this is the front of the simulation tomcat}} catch (Exception e) {System.out.println ("Error." + e); }   } public static void Main (string[] args) {new Socketserver (); }  }
The above piece of code, in Tomcat, is essentially a acceptor thread.
2. the worker thread that corresponds to Tomcat is actually the Serverthread class : public class Serverthread extends Thread {private static int number = 0;//save customer count for this process socket socket = NULL;//save with this line   Process-related socket object public serverthread (socket socket, int clientnum) {this.socket = socket; } public void Run () {try { BufferedReader in = new BufferedReader (new InputStreamReader (socket . getInputStream ())); PrintWriter out = new PrintWriter (Socket.getoutputstream ());//Get stream from socketBufferedReader sysin = new BufferedReader (new InputStreamReader (system.in));    System.out.println ("[Client" + number + "]:" + in.readline ()); String Line; Line = Sysin.readline ();//streaming Readwhile (!line.equals ("Bye")) {//If the string is "Bye", the loop is stopped out.println (line); Out.flush (); Streaming Write and RefreshSystem.out.println ("[Server]:" + line);      System.out.println ("[Client" + number + "]:" + in.readline ());     line = Sysin.readline (); } out.close (); Close the socket output stream in.close (); Close the socket input stream socket.close ();    Close the socket} catch (Exception e) {System.out.println ("Error." + e); }   }    }
the above-mentioned worker threads are handled directly here, and in Tomcat the process is very complex and the subsequent code extends to the back-end container of Tomcat.
To summarize, in fact, the bio model is very clear, the first-thread a request, from the above example has been seen very clearly,
the read of the socket is a streaming read, which is the flow from the socket, and the stream is read directly through the Java,io.

Nio:public class Nioserver {/* ID number */private int flag = 0;      /* Buffer size */private int BLOCK = 4096;      /* Accept Data buffer */private Bytebuffer Sendbuffer = Bytebuffer.allocate (BLOCK);      /* Send data buffer */private Bytebuffer Receivebuffer = Bytebuffer.allocate (BLOCK);        Private Selector Selector; public nioserver (int port) throws IOException { //======> This is equivalent to the acceptor thread in Tomcat, except that the channel is repackaged again, passing in the Selectionkey,       //Open server Socket channel          Serversocketchannel Serversocketchannel = Serv Ersocketchannel.open ();         //server configured for non-blocking          serversocketchannel.configureblocking ( FALSE);         //retrieving server sockets associated with this channel          ServerSocket serversocket = ServerS Ocketchannel.socket ();         //Binding of services          Serversocket.bind (New Inetsocketaddress (PO RT));         //through the open () method to find selector          selector = Selector.open ();         //Register to selector, wait for connection          Serversocketchannel.register ( selector, selectionkey.op_accept);          System.out.println ("Server Start----8888:");     }       private void Listen () throws IOException {  //======>  this corresponds to the poller thread in Tomcat, to the front wrapper Selectionkey is polled and passed through Handlekey to the worker thread .        while (true) {            //Select a set of keys and the corresponding channel is open &NBSP;&NBS P           selector.select ();             //Returns the selected key set for this selector.              set<selectionkey> Selectionkeys = Selector.selectedkeys ();              iterator<selectionkey> Iterator = Selectionkeys.iterator ();              while (Iterator.hasnext ()) {           &nbs P             Selectionkey Selectionkey = Iterator.next ();                  iterator.remove ();                  Handlekey (Selectionkey);              {        }     } &NBSP;&NBSP;&N bsp;   //Processing requests &nbsp //======> This is directly below the worker thread, into the Tomcat container and eventually returns the result of the call.
    private void Handlekey (Selectionkey selectionkey) throws IOException {        // Accept request          Serversocketchannel server = null;          Socketchannel client = null;          String Receivetext;          String SendText;          int count=0;         //test whether the channel for this key is ready to accept the new socket connection.          if (selectionkey.isacceptable ()) {            //return The channel for which this key is created.              Server = (Serversocketchannel) selectionkey.channel ();             //Accept connections to this channel socket.             ///The socket channel returned by this method (if any) will be in blocking mode.              client = Server.accept ();             //configured for non-blocking              client.configureblocking (false);              //Register to selector, wait for connection Client.register (selector, selectionkey.op_read); } else if (Selectionkey.isreadable ()) {//returns the channel to which this key was created.              Client = (Socketchannel) selectionkey.channel ();              Empty the buffer for the next read of Receivebuffer.clear ();               Reads the data sent by the server into the buffer in count = Client.read (Receivebuffer);                  if (Count > 0) {receivetext = new String (Receivebuffer.array (), 0,count); SYSTEM.OUT.PRINTLN ("Server side accepts client data--:" +receivetext); Client.register (selector, selectionkey.op_write); }} else if (Selectionkey.iswritable ()) {//buffer is emptied for next write Sendbuffer.clear ();              Returns the channel for which this key was created.              Client = (Socketchannel) selectionkey.channel ();              sendtext= "Message from server--" + flag++; Enter Data Sendbuffer.put (Sendtext.getbytes ()) into the buffer; //Reset the buffer flag, because put the data mark is changed in order to read from the data sent to the server, it will be reset sendbuffer.flip ();  Output to channel client.write (Sendbuffer); SYSTEM.OUT.PRINTLN ("server-side sends data to client--:" +sendtext); Client.register (selector, selectionkey.op_read);}}/** * @param args * @throws IOException */public static void main (string[] args) thro          WS IOException {//TODO auto-generated method Stub int port = 8888;          Nioserver Server = new Nioserver (port);      Server.listen (); }  }
To summarize, several stages of the NIO program mentioned above can reflect the working mode of Tomcat's NIO front-end thread pool, except that the code above is serial, and Tomcat is handed over through several thread pools, and each thread pool needs to share some data for delivery.
Finally, in the author's program to write NiO several errors, remind you, we need to pay attention to:
1. The above in each Selectkey poll, need to pay attention to the last sentence, for example, when the Accept event occurs, Socketchannel need to change their own concerns, because this time if you are also concerned about the accept event, it is equivalent to nothing happens, Because this time Socketchannel has sent the data again, the equivalent of only monitoring read and write events to get the socket input and output. As a result, you can seewhen the Accept event occurs: Client.register (selector, selectionkey.op_read);
re-register the Read event. Look at it again .The last word of the read event, registered as the write event Client.register (selector, selectionkey.op_write);
this is because after the read is finished, it is necessary to send some content immediately, so we need to changeSocketchannel The operating mode, set it to write mode. Similarly, after the read event, the same immediately read the client's data, this will have to re-register the read event, for the above-mentioned channel pattern changes, Tomcat is the package into the Niochannel, constantly based on the socket operation mode to switch.
2. Another notable thing is that the flip operation of buffer buffers, the first thing to note is the three buffer properties:
These three properties are different depending on the read mode and the write modeCapacity:
  • capacity, whether in write mode or read mode, is fixed

  • Position: refers to the current location
  • When the data is read from the position in buffer, the position moves forward to the next readable position.

    limit: Maximum read/ Write Restrictions
    . In other words, you can read all the previously written data (the limit is set to the number of written data, this value is position in write mode)

we understand the above principle, it is not difficult to understand why the above buffer often to flip, theflip method to switch buffer from write mode to read mode. Calling the flip () method resets position back to 0 and sets the limit to the value of the previous position, which is equivalent to preparing the read, and the sendbuffer in the preceding code is immediately: /output to channel Client.write (Sendbuffer); in this client.write method, the actual byte is read from buffer and then sent to the socket buffer, so although this seemingly does not seem to read the meaning, but actually hidden read, so the flip operation is also necessary.



From for notes (Wiz)

D.bio connector vs. NIO connector two

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.