Netty Channel Interface Noun Understanding

Source: Internet
Author: User
Tags map data structure readable

Use non-blocking Serversocketchannel, Socketchannel instead of ServerSocket and sockets

When using traditional serversocket and sockets, programs are often blocked.
For example, Serversocket.accept (), Socket.getinputstream (), will block the accept () method until the client socket is connected or interrupted otherwise
The read () method is also so unless there is enough data in the input stream, the method waits until the data arrives. In the ServerSocket and socket mode, the server side often assigns a thread to each client (socket), Each thread is likely to be in a long blocking state. And too many threads can affect the performance of the server. In JDK1.4, non-blocking communication is introduced, which enables the server to handle requests for all client sockets with only one thread.
Here are a few of the core classes you need to use
Serversocketchannel:serversocket class, which supports blocking traffic and non-blocking traffic.
Socketchannel:socket class, which supports blocking traffic and non-blocking traffic.
Selector: Monitor incoming client connection readiness events for Serversocketchannel, monitor Connection server readiness for Socketchannel, read-ready, and write-ready events.
Selectionkey: Represents the handle of Serversocketchannel and Socketchannel registering events to Selector. When a Selectionkey object is in the Selected-keys collection of the Selector object, it means that the event associated with this Selectionkey object occurs. There are several static constants in the Selectionkey class
Selectionkey.op_accept-> Client Connection ready event equals listener serversocket.accept () returns a socket
Selectionkey.op_connect-> ready to connect the server is ready to be similar to the above, except for the equivalent of the socket listening to the socket.connect ()
Selectionkey.op_read-> Read-ready event, which indicates that the input stream already has readable data and can perform a read operation.
Selectionkey.op_write-> Write-ready event

Here is the server side:
Selector Selector = Selector.open (); static method Instantiation of Selector
Serversocketchannel Serverchannel = Serversocketchannel.open ();
Serverchannel.configureblocking (FALSE); is set to Non-blocking, and if True then the traditional blocking method
Serverchannel.socket (). bind (New Inetsocketaddress (port)); Binding IP and Port
Serverchannel.register (selector, selectionkey.op_accept); Registering Op_accept Events
New Serverthread (). Start (); Open a thread to handle all requests
The Run method in Serverthread
View Plainprint?
public void Run ()
{
while (true)
{
Try
{
Selector.select ();
set<selectionkey> keys = Selector.selectedkeys ();
Iterator<selectionkey> iter = Keys.iterator ();
Socketchannel SC;
while (Iter.hasnext ())
{
Selectionkey key = Iter.next ();
if (key.isacceptable ()); New Connection
else if (key.isreadable ());//readable
Iter.remove (); To remove the event from the keys
}
catch (Exception e)
{
E.printstacktrace ();
}
}
}
of which in isacceptable () through the Serversocketchannel SSC = (serversocketchannel) key.channel (); Socketchannel sc = ssc.accept (); Get the client's Socketchannel
In IsReadable () Socketchannel sc = (socketchannel) key.channel (); Get Socketchannel.
You can read and write with write () read () in a Socketchannel object except that the object being manipulated is no longer a byte[] string, but Bytebuffer

The client is basically the same
selector = Selector.open ();
Channel = Socketchannel.open (new inetsocketaddress (port));
Channel.configureblocking (FALSE);
Channel.register (Selector,selectionkey.op_connect);
New Clientthread (). Start ();
Run method
while (true)
{
Selector.select ();
set<selectionkey> keys = Selector.selectedkeys ();
Iterator<selectionkey> iter = Keys.iterator ();
while (Iter.hasnext ())
{
Selectionkey key = Iter.next ();
if (key.isconnectable ());//Connection Successful & Normal
else if (key.isreadable ())//readable
Iter.remove ();
}
The current Socketchannel object can be obtained by means of Key.channel ();

To sum up, in fact, the blocking becomes non-blocking, and actually it's handled with a while dead loop.
First, the event is Seleector.select (), and if there is an event, whatever it is, it is given to the circulation body to handle the different processing in the circulation body.
and multiple sockets are managed through a seleector agreement
While (waits until there is a receive connection ready event, a read-ready event or a write-ready event) {//Blocking
if (with customer connection)
Receive the customer's connection; Non-blocking
if (there is readable data in the input stream of a Socket)
Reading data from the input stream; Non-blocking
if (the output stream of a Socket can write data)
Writes data to the output stream; Non-blocking
}
Like this, the above processing process takes the form of polling, and when a certain operation is in place, it does so, or it looks to see if there are other ready operations to execute. Threads do not go into a blocking state because one operation is not ready, and have been innocently waiting for the operation to be ready.

http://blog.csdn.net/kongxx/article/details/7288896

-----------------------------------------------------

---1.Channel
Channel is responsible for data reading, writing objects, somewhat similar to the old IO inside the stream. The difference between it and stream, channel is two-way, can write or read, and the stream should be divided into OutStream and InputStream. In NiO, users should not read and write data directly from channel, but instead read and write data to channel via buffer.
A channel can provide users with a few of the following information
(1) The current state of the channel, such as Open or closed
(2) Channelconfig object that represents some of the channel parameters, such as buffersize

(3) All I/O operations supported by channel (such as Read,write,connect.bind) and Channelpipeline (explained below)


2.ChannelConfig
Channel parameters are stored in the map data structure


3.CHANNELEVENT&NBSP
Channelevent A broad view of channel related events, whether it is divided into upstream events and downstream events two big chunks, which should be noted here, If the server is the main body, the process from client data to server is upstream, while server to client data transfer process is called downstream, and if the client is the main body, The process from server to client is upstream to the client, and the client to server process is downstream to the client. &NBSP
upstream events include:  
messagereceived:---messageevent  when information is accepted;
Exceptioncaught:---exceptionevent  when an exception is generated---channelstateevent  when the
Channelopen:channel is opened;
When the Channelclosed:channel is closed---channelstateevent 
Channelbound:channel is turned on and ready to be connected but not connected--- CHANNELSTATEEVENT&NBSP
Channelunbound:channel is opened and not ready to connect---channelstateevent 
When the Channelconnected:channel is connected---channelstateevent 
Channeldisconnected:channel When the connection is disconnected--- CHANNELSTATEEVENT&NBSP
Channelinterestchanged:channel When the interestops is changed------channelstateevent 
Writecomplete: When writing to the remote end of the completion--writecompletionevent 

Downstream events include:
Write: Send a message to channel when--messageevent
Bind: Binds a channel to the specified local address--channelstateevent
Unbind: Unbind the current local port--channelstateevent
Connect: Attach the channel to the remote machine--channelstateevent
Disconnect: Disconnect channel from remote machine--channelstateevent
Close: Turn off channel--channelstateevent

Note that there is no open event here because when a channel is created by ChannelFactory, channel is always turned on.

In addition, there are two event types where the parent channel exists as a child channel
Childchannelopen: Channel is opened---channelstateevent
Childchannelclosed: Channel is closed---channelstateevent

4.ChannelHandler
Channel is responsible for the transmission of data carrier, then the data must be processed according to requirements, then the use of Channelhandler
Different processing can build different channelhandler, then put into channelpipeline
In addition, a channelevent trigger is required to reach the Channelhandler, so the following two sub interfaces are available depending on the event Channelupstreamhandler
and Channeldownstreamhandler.
A channelhandler usually needs to store some state information as a judgment message, and the common practice is to define a variable
Like what

public class Dataserverhandler extends {@link Simplechannelhandler} {
*
* <b>private Boolean loggedin;</b>
*
* {@code @Override}
* public void messagereceived ({@link Channelhandlercontext} ctx, {@link messageevent} e) {
* {@link Channel} ch = E.getchannel ();
* Object o = e.getmessage ();
* IF (o instanceof loginmessage) {
* Authenticate ((loginmessage) o);
* <b>loggedin = true;</b>
*} else (o instanceof getdatamessage) {
* if (<b>loggedIn</b>) {
* Ch.write (Fetchsecret (getdatamessage) o));
*} else {
* FAIL ();
*             }
*         }
*     }
*     ...
* }

Create a new handler instance per channel.
*//The {@link bootstrap#setpipelinefactory (channelpipelinefactory)}.
* Public class Dataserverpipelinefactory implements {@link Channelpipelinefactory} {
* Public {@link channelpipeline} getpipeline () {
* Return {@link channels}.pipeline (<b>new dataserverhandler () </b>);
*     }
* }


In addition to this, each channelhandler can get or set data from the Channelhandlercontext, so the following approach is to use channelhandlercontext <

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.