The use of Niosocket

Source: Internet
Author: User

Don't know what to say (? _)?

Serversocketchannel and Socketchannel, which correspond to the original serversocket and sockets.

Buffer, channel and selector

Buffer is the goods to be sent, the channel is the delivery operator (or to a certain area of the truck), selector is the station's sorter.

Niosocket in use first to create Serversocketchannel, and then register selector, then you can use Selecto to receive requests and processing.

Serversocketchannel can be created using its own static factory method open. Each serversocketchannel corresponds to a serversocket, which can call its socket method to get, typically using the ServerSocket obtained to bind the port. Serversocketchannel can be set using the Configureblocking method, if blocking mode is used, if the non-blocking mode can be set with configureblocking (false), After you set the nonblocking mode, you can call the Register method to register selector to use (blocking mode is not available for selector).


Selector can be created by its static factory method open and registered to Serversocketchannel or Socketchannel via the channel's Register method. After registration selector can wait for the request through the Select method, the Select method has a long parameter, which represents the maximum wait time, and if the request receives the corresponding operation during that time, returns the number of requests that can be processed, or returns 0 after the timeout. The program continues to go down, if the parameter passed in is 0 or if an overloaded method with no parameters is called, the Select method takes blocking mode until a request with the appropriate action appears. When a request is received, selector calls the Selectedkeys method to return the collection of Selectionkey.

Selectionkey saves the channel and selector that handle the current request, and provides different types of operations. The channel can select a specific operation from the second parameter of register when registering selector, here the operation is defined in the Selectionkey, there are 4 kinds: · Selectionkey.op_accept Accept Request Operation · Selectionkey.op_connect Connection Operation · Selectionkey.op_read Read Operation · Selectionkey.op_write write operations only if the corresponding operation is registered in the Register method selector will be concerned with the request of the corresponding type operation. Channel and selector do not have a relationship with whom, as if a sorter can pick up goods for multiple areas and each region can have multiple sorters to sort it out, as if it were a many-to-many relationship in the database, but selector the sorter is more finely sorted, It can be sorted according to different types, the result of sorting is saved in Selec-tionkey, and the channel and selector can be obtained by Selectionkey channel method and selector method respectively. The isacceptable, isconnectable, IsReadable, and iswritable methods can also be used to determine what type of operation. The processing of the service side in Niosocket can be divided into 5 steps: 1) Create Serversocketchannel and set the corresponding parameters. 2) Create the selector and register on the Serversocketchannel. 3) Call Selector's Select method to wait for the request. 4) Selector Returns the Selectionkey collection using Selectedkeys after receiving the request. 5) Use Selectionkey to obtain channel, selector, and operation types and perform specific operations.
 Public classNioserver { Public Static voidMain (string[] args)throwsException {//Create Serversocketchannel, listen on port 8080Serversocketchannel SSC (); Ssc.socket (). Bind (NewInetsocketaddress (8080));//to bind a port using the obtained ServerSocket//set to non-blocking mode, blocking mode cannot be used selectorSsc.configureblocking (false); //registering selectors for SSCSelector Selector ();        Ssc.register (selector, selectionkey.op_accept); //Creating the ProcessorHandler Handler =NewHandler (1024);  while(true){            //waits for a request, each time waits for 3 seconds, the thread continues to run down after 3s, and if the pass-through 0 or no parameter is blocked            if( (3000) ==0) {System.out.println ("Wait for the request to time out ..."); Continue; } System.out.println ("Processing requests ..."); //get the Selectionkey you want to processIterator<selectionkey> Keyiterator =Selector.selectedkeys (). iterator ();  while(Keyiterator.hasnext ()) {Selectionkey (); Try{//When a connection request is received//If the request operation is accepted                    if(Key.isacceptable ()) {handler.handleaccept (key); }                    //if it is a read data operation                    if(Key.isreadable ()) {handler.handleread (key); }                    //and a isconnectable,iswritable .}Catch(IOException ex) {//after processing, remove the currently used key from the pending Selectionkey iteratorKeyiterator.remove (); Continue;            } keyiterator.remove (); }        }    }    Private Static classhandler{Private intbuffersize = 1024; PrivateString localcharset = "UTF-8";  PublicHandler () {} PublicHandler (intbuffersize) {             This(BufferSize,NULL); }         PublicHandler (String localcharset) { This(-1, Localcharset); }         PublicHandler (intbuffersize, String localcharset) {            if(BufferSize > 0)                 This. buffersize =buffersize; if(Localcharset! =NULL)                 This. Localcharset =Localcharset; }         Public voidHandleaccept (Selectionkey key)throwsioexception{Socketchannel SC=( (Serversocketchannel) ()). Accept (); Sc.configureblocking (false);        Sc.register (Key.selector (), Selectionkey.op_read, Bytebuffer.allocate (buffersize)); }         Public voidHandleread (Selectionkey key)throwsioexception{//Get channelSocketchannel sc =(Socketchannel) (); //get buffer and resetBytebuffer buffer =(Bytebuffer) key.attachment ();            Buffer.clear (); //do not read the content is closed            if( (buffer) = =-1) {sc.close (); }Else{                //convert buffer to read StateBuffer.flip (); //The value received in buffer is encoded in localcharset format and saved to receivedstringString receivedstring =charset.forname (Localcharset). Newdecoder (). Decode (buffer). toString (); System.out.println ("Received from Cient:" +receivedstring); //returning data to the clientString sendstring = "received data:" +receivedstring; Buffer=Bytebuffer.wrap (Sendstring.getbytes (Localcharset));                Sc.write (buffer); //Close SocketSc.close (); }        }    }}

The above process has been commented, the main method to start monitoring, when the listener hears the request according to the state of Selectionkey to the internal class handler for processing, handler can be overloaded by the construction method to set the encoding format and the maximum value of each read data. Handler is used in the process of Buffer,buffer is a class in the Java.nio package, dedicated to storing data, buffer has 4 properties is very important, they are:Capacity: capacity, that is, buffer can save the number of elements, set at the time of creation, the use of the process can not be changed;Limit: The upper limit can be used, the value of limit and capacity are the same when you start creation, and if you set a value for limit, limit becomes the maximum accessible value, and its value cannot exceed capacity. For example, a buffer capacity of capacity is 100, indicating a maximum of 100 data can be saved, but now only to write 20 data and then to read, when reading the limit will be set to 20;Position: The index position at which the currently manipulated element is located, position starting at 0, with the get and put methods automatically updated;Mark: Used to temporarily save the value of position, position saved to mark can be modified and related to the operation, after the operation can be reset method to restore Mark's value to position. For example, a total of 20 data is saved in buffer, the position of position is 10, and now you want to read data between 15 and 20, you can call Buffer#mark () to save the current position to mark, and then call buffer# Position (15) points the position to the 15th element, then it can be read, and after reading it, call Buffer#reset () to restore position to 10. The mark default value is-1, and its value must be less than position, and if Buffer#position (Int newposition) is called, the incoming newposition will be set to-1 if it is smaller than mark.   The size relationship of these 4 attributes is: mark<=position<=limit<=capacity. By understanding these 4 attributes, buffer is easy to understand.   Our nioserver here uses the clear and flip methods, and the clear function is to reinitialize the limit, position, and mark three properties, allowing Limit=capacity, position=0, and Mark=-1. The Flip method works like this: Save a data position plus 1 when you save the data, and if you want to read it, you need to set the best position position to limit, then set the position to 0 so you can read the saved data. The flip method is to do this, and the code for the two methods is as follows: 
 //  Java.nio.Buffer  public  final   Buffer Clear () {position 
    = 0;     Limit  = capacity;     Mark  = -1;  return  this  ;  public  final   Buffer Flip () {Limit  = position;     Position  = 0;     Mark  = -1;  return  this  ; } 

The use of Niosocket

Related Article

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: 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.