Java NiO (reactor, selector, selectionkey)

Source: Internet
Author: User

Socketchannel vs. serversocketchannel

  • Parent class: selectablechannel. Channel represents a channel that can perform Io operations (for example, through filechannel, we can perform read and write operations on files)
  • Serversocketchannel is mainly used in the server to receive client connection requests.
    Socketchannel is used to read and write data, and can also be used to send link requests from clients.
  • These socketchannels are used to read and write data. The above serversocketchannel is only responsible for receiving connection requests.
  • Channel

 

 

Channel vs. Selector

  • The channel must be registered on the selector. A channel can be registered with one or more selectors for asynchronous Io operations.

Channel. Register (selector, selectionkey. op_accept );

Channel. Register (selector, XXX, object); // attachment is stored in the returned selectionkey

Channel. keyfor (selector); // return the selectionkey corresponding to the registration relationship of the channe on the selector. If no registration relationship exists, null is returned.

  • Selector can monitor the IO status of multiple selectablechannels at the same time, which is the core of asynchronous Io.

Selector. open (); // static method to create a selector instance

Selector. Select (); // selector calls select () to extract events from the registered channel for processing. Monitor all registered channels. When registered Io operations are available, this function returns and adds the corresponding selectionkey to the selected-key set.

Selector. Keys (); // all the channels registered on this Selector

Selector. selectedkeys (); // All channels that can perform Io operations are monitored using the select () method.

 

Selectionkey

  • Represents the registration relationship between selector and selectablechannel

Key. Attachment (); // return the attachment of selectionkey. attachment can be specified when the channel is registered.

Key. Channel (); // return the channel corresponding to the selectionkey.

Key. selector (); // returns the selector corresponding to the selectionkey.

Key. interestops (); // return the bit mask that represents the IO operations to be monitored by the selector.

Key. readyops (); // returns a bit mask, representing Io operations that can be performed on the corresponding channel.

 

 

Demo1: how to accept connections at the underlying layer of the server

Int n = selector. Select (); // obtain the number of events captured by selector.
If (n> 0) {// The action is performed only when the event is captured.
Set selectedkeys = selector. selectedkeys (); // gets the collection of captured events
Iterator I = selectedkeys. iterator ();
While (I. hasnext ())
{
Selectionkey S = (selectionkey) I. Next (); // one-to-one processing of events

// After a key is processed, it is removed from the ready keys list.
I. Remove ();
If (S. isacceptable () // indicates that the event is an op_accept event.
{
// Obtain the newly registered serversocketchannel from Channel.
// Obtain the new socketchannel for the request
Socketchannel SC = (serversocketchannel) S. Channel (). Accept (). socket (). getchannel ();

SC. configureblocking (false); // sets the socketchannel as a non-blocking method.
SC. Register (selector, selectionkey. op_read | selectionkey. op_write );
// Register the new socketchannel to the selector. The registration event is op_read and op_write.
}
Else
{
// Perform other operations
}
}
}

 

Demo2: how to read data on the channel at the bottom layer of the server

Selectionkey S = (selectionkey) I. Next (); // one-to-one processing of events

// After a key is processed, it is removed from the ready keys list.
I. Remove ();
Bytebuffer clientbuffer = bytebuffer. Allocate (4096 );
If (key. isreadable () {// read information
Socketchannel channel = (socketchannel) Key. Channel (); // obtain the corresponding socketchannel
Int COUNT = channel. Read (clientbuffer); // read data into clientbuffer
If (count> 0) {// when data is read
Clientbuffer. Flip (); // reverse this buffer
Charbuffer = decoder. Decode (clientbuffer); // decodes the characters in the buffer if needed
... // Process data
}
}

 

Demo3: how to initiate a connection and write data at the underlying layer of the Client

Inetsocketaddress ADDR = new inetsocketaddress (host, Port );
// Generate a socketchannel
SC = socketchannel. open ();
// Connect to the server
SC. Connect (ADDR); // connect to the server

If (SC. finishconnect () {// when the connection is successful, perform the corresponding operation
Bytebuffer buffer =... // prepare data
Buffer. filp (); // reverse this buffer
While (w_buff.hasremaining () // send data to the server
SC. Write (w_buff );

 

Learning documents:

Http://www.iteye.com/topic/40489

Http://blog.csdn.net/derekjiang/article/details/4465697

Http://blog.csdn.net/derekjiang/article/details/4470175

Http://www.cnblogs.com/freedom-elf/archive/2011/08/11/2135015.html

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.