Network communication framework Apache MINA

Source: Internet
Author: User

Apache MINA (Multipurpose Infrastructure for network applications) is a relatively new project for the Apache organization that provides a very convenient framework for developing high-performance and high-availability Web applications. The current release of the MINA version supports TCP/UDP application development and serial communication programs based on Java NIO technology.

Application Layer for Mina:



A well-developed open-source framework will always be able to minimize intrusion and find the right location throughout the project, rather than having too much impact on the architectural design of the entire project, and Figure 1 is the MINA application layer. And the DEMO in the previous section, we can see that Mina very good to isolate the business code and the underlying communication, we have to do is to establish a good listening, and then write the business logic we need to implement is OK.

Internal flow of MINA:



(1) Ioservice: This interface is responsible for the establishment of sockets on a thread, having its own Selector, and monitoring whether there is a connection being established.

(2) Ioprocessor: This interface is responsible for checking to see if there is data read and write on the channel, that is, it also has its own selector, which is a difference from when we use Java NIO encoding, usually in Java NIO encoding, we use a Selector, that is, does not differentiate between Ioservice and ioprocessor two functional interfaces. In addition, Ioprocessor is also one of the core components of the MINA framework. When the MINA framework is started, a thread pool is specifically generated to invoke the filter registered on the Ioservice, and Iohandler is called after the filter chain. By default, Ioprocessor uses n+1 threads to take turns asking whether the monitored ports have data transfers, where n is the number of cores in the CPU. According to the general multithreaded design concept, ioprocessor the number of threads is the better, but in fact not, because everyone knows that the operation of IO is very resource-intensive, so the number of ioprocessor threads in the project should be based on actual needs, and this number can be generated in the Ioacceptor the object when it is set. Egioacceptor acceptor = new Niosocketacceptor (N);

(3.) IoFilter: This interface defines a set of interceptors that can include log output, blacklist filtering, or even write permission control in the filter chain using AOP. Functions such as encoding of data (write direction) and decoding (read direction), where the encode and decode of data are the most important and are the main concerns when you use Mina.

(4.) Iohandler: This interface is responsible for writing business logic, which is where the data is received and sent. If you write the business process, and write good business interface, the real time, only need to replace here, and once again witnessed the MINA of the complete layering.

Where the Ioservice interface is dedicated to a thread polling for new connections, and if a connection is generated notifies Ioprocessor, and Ioprocessor n+1 a thread to check if the connection has data read and write. Once a connection is generated and data is read and written, the decode or encode is notified, the message is decoded or encoded, and the processed message is handed over to the business class for business processing. Where Ioprocessor is the allocation of processing requests, including selection of Selector, timeout validation, status records, and so on. In short, this class works in conjunction with Ioservice, encapsulating the implementation of the NIO bottom layer and supporting the functionality within the MINA framework.

Combined with examples, and according to the above-mentioned text, we can easily summarize the use of MINA programming a few general steps:

Create a class that implements the Ioservice interface

Set up a filter that implements the IoFilter interface (if necessary)

Set up a processing class for an Iohandler interface implementation to handle events (required)

Bind a port to Ioservice to start working


Note: It is important to note that because Ioprocessor is also the equivalent of a polling mechanism, which results in the last state of the same connection (the object generated by the Iosession class in MINA) must be saved when the message is too long, or otherwise causes the message not to be transmitted at one time. In order to intercept a completed message, this is the core work that decode (encoder) needs to do.


Use of Mina:

Mina TCP Service Side
Package com.mina.test;

Import Java.util.Date;

Import Org.apache.mina.core.service.IoHandlerAdapter;
Import Org.apache.mina.core.session.IdleStatus;
Import org.apache.mina.core.session.IoSession;

public class Timeserverhandler extends Iohandleradapter {
@Override
public void Sessioncreated (Iosession session) throws Exception {
SYSTEM.OUT.PRINTLN ("Server creates connection with client ...");
Super.sessioncreated (session);
}

@Override
public void sessionopened (Iosession session) throws Exception {
SYSTEM.OUT.PRINTLN ("Server Open with Client connection ...");
Super.sessionopened (session);
}

@Override
public void Sessionclosed (Iosession session) throws Exception {
SYSTEM.OUT.PRINTLN ("Server-to-client connection closed ...");
Super.sessionclosed (session);
}

@Override
public void Messagesent (iosession session, Object message) throws Exception {
SYSTEM.OUT.PRINTLN ("server sends information successfully ..." +message.tostring ());
Super.messagesent (session, message);
}

public void Exceptioncaught (iosession session, Throwable Cause)
Throws Exception {
SYSTEM.OUT.PRINTLN ("Server send Exception ..." +cause.getmessage ());
Cause.printstacktrace ();
}

public void Messagereceived (iosession session, Object message)
Throws Exception {
String STRMSG = message.tostring ();
SYSTEM.OUT.PRINTLN ("The data received by the server is:" +strmsg);
if (Strmsg.trim (). Equalsignorecase ("quit")) {
Session.close ();
Return
}
Date date = new Date ();
Session.write (Date.tostring ());
}

public void Sessionidle (iosession session, Idlestatus status)
Throws Exception {
SYSTEM.OUT.PRINTLN ("Service side enters idle state ... "+ session.getidlecount (status));
}
}


Package com.mina.test;

Import java.io.IOException;
Import java.net.InetSocketAddress;
Import Java.nio.charset.Charset;

Import Org.apache.mina.core.service.IoAcceptor;
Import Org.apache.mina.core.session.IdleStatus;
Import Org.apache.mina.filter.codec.ProtocolCodecFilter;
Import Org.apache.mina.filter.codec.textline.TextLineCodecFactory;
Import Org.apache.mina.filter.logging.LoggingFilter;
Import Org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class Minatimeserver {

private static final int PORT = 6488;

public static void Main (string[] args) throws IOException {

Listen for incoming TCP connections, build a monitor
Ioacceptor acceptor = new Niosocketacceptor ();
Setting up interceptors
Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ());
Acceptor.getfilterchain (). AddLast (
"Codec",
New Protocolcodecfilter (New Textlinecodecfactory (Charset
. forname ("GBK")));
Set up processing classes
Acceptor.sethandler (New Timeserverhandler ());
Setting up the configuration
Acceptor.getsessionconfig (). Setreadbuffersize (2048);
Acceptor.getsessionconfig (). Setidletime (Idlestatus.both_idle, 10);

A bound listening port that can be bound more than once, or can be bound more than one at a time.
Acceptor.bind (New Inetsocketaddress (PORT));
SYSTEM.OUT.PRINTLN ("Server started successfully ... The port number is: "+port);

}
}


Mina TCP Client
Package com.mina.test;

Import Org.apache.mina.core.buffer.IoBuffer;
Import Org.apache.mina.core.service.IoHandlerAdapter;
Import Org.apache.mina.core.session.IdleStatus;
Import org.apache.mina.core.session.IoSession;
Import org.apache.mina.proxy.utils.ByteUtilities;


public class Timeclienthandler extends Iohandleradapter {

@Override
public void messagereceived (iosession iosession, Object message)
Throws Exception {
Iobuffer bbuf = (iobuffer) message;
byte[] Byten = new Byte[bbuf.limit ()];
Bbuf.get (Byten, Bbuf.position (), Bbuf.limit ());
SYSTEM.OUT.PRINTLN ("Client received message" + Byteutilities.ashex (Byten));
}
@Override
public void Exceptioncaught (iosession session, Throwable Cause)
Throws Exception {
SYSTEM.OUT.PRINTLN ("client exception");
Super.exceptioncaught (session, cause);
}
@Override
public void Messagesent (iosession iosession, Object obj) throws Exception {
SYSTEM.OUT.PRINTLN ("client message sending");
Super.messagesent (iosession, obj);
}
@Override
public void sessionclosed (Iosession iosession) throws Exception {
SYSTEM.OUT.PRINTLN ("Client session shutdown");
Super.sessionclosed (iosession);
}
@Override
public void sessioncreated (Iosession iosession) throws Exception {
SYSTEM.OUT.PRINTLN ("Client session creation");
Super.sessioncreated (iosession);
}
@Override
public void Sessionidle (Iosession iosession, Idlestatus idlestatus)
Throws Exception {
SYSTEM.OUT.PRINTLN ("Client session hibernation");
Super.sessionidle (Iosession, idlestatus);
}
@Override
public void sessionopened (Iosession iosession) throws Exception {
SYSTEM.OUT.PRINTLN ("Client session open");
Super.sessionopened (iosession);
}

}


Package com.mina.test;

Import java.net.InetSocketAddress;

Import Org.apache.mina.core.buffer.IoBuffer;
Import Org.apache.mina.core.future.ConnectFuture;
Import Org.apache.mina.core.service.IoConnector;
Import org.apache.mina.core.session.IoSession;
Import Org.apache.mina.transport.socket.nio.NioSocketConnector;

public class Minatimeclient {

private static final int PORT = 6488;
private static Ioconnector connector;
private static iosession session;

public static void Main (string[] args) throws Exception {

Timeclienthandler clienthandler=new Timeclienthandler ();
Connector = new Niosocketconnector ();
Set up processing classes
Connector.sethandler (ClientHandler);
Connectfuture connfuture = connector.connect (new inetsocketaddress ("localhost", PORT));
Connfuture.awaituninterruptibly ();
Session = Connfuture.getsession ();
Clienthandler.sessionopened (session);
SYSTEM.OUT.PRINTLN ("TCP client Start");

for (int j=0;j<5;j++) {//Send two times
byte[] BTS = new BYTE[20];
for (int i = 0; i <; i++) {
Bts[i] = (byte) i;
}
Iobuffer buffer = iobuffer.allocate (20);
Automatic expansion
Buffer.setautoexpand (TRUE);
Auto Shrink
Buffer.setautoshrink (TRUE);
Buffer.put (BTS);
Buffer.flip ();
Session.write (buffer);
Thread.Sleep (2000);
}
Close the session until all threads have finished processing
Connector.dispose (TRUE);

}

}

Network communication framework Apache MINA

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.