Original link: http://www.cnblogs.com/xuekyo/archive/2013/03/06/2945826.html
Apache Mina is a framework that helps users develop high-performance and highly scalable network applications. It provides an abstract, event-driven, asynchronous API based on the TCP/IP and UDP/IP Protocols of Java NIO technology.
Apache MINA is a network application framework that enables users to easily develop high-performance, highly scalable network applications. It provides an abstract, event-driven, asynchronous API on top of various transport protocols, such as TCP/IP and UDP/IP, through Java NIO.
Introduction to the Mina package:
| Org.apache.mina.core.buffer |
Iobuffer for buffers |
Org.apache.mina.core.service org.apache.mina.transport.* |
Service used to provide the connection |
| Org.apache.mina.core.session |
Session to provide both sides of the state |
Org.apache.mina.core.filterchain Org.apache.mina.filter.* |
Filter chain and various interceptors (between Ioservice and Iohandler) to intercept all IO events and requests |
| Org.apache.mina.handler.* |
handler for handling IO events |
| Org.apache.mina.core.future |
Future for implementing asynchronous IO operations |
| Org.apache.mina.core.polling |
Polling for implementing IO polling |
| Org.apache.mina.proxy.* |
Proxy for implementing an agent |
First introduce several important interfaces of Mina:
- Ioserviece: This interface is responsible for setting up sockets on a thread, having its own Selector, and monitoring whether there is a connection being established.
- Ioprocessor: This interface is responsible for checking that data is read and written on the channel on another thread, which means it 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 responsible for invoking the filter registered on Ioservice and calling Iohandler after the filter chain.
- Ioaccepter: Equivalent to server-side in a network application
- Ioconnector: equivalent to Client
- Iosession: A connection instance to the server side of the current client
- Iohandler: This interface is responsible for writing business logic, which is where the data is received and sent. This is also the actual development process requires users to write their own part of the code.
- IoFilter: The filter is used for suspending the communication layer interface with the business layer interface, which defines a set of interceptors that can include functions such as log output, blacklist filtering, encoding of data (write direction) and decoding (read direction), where the encode of the data and Decode is the most important and the main concern when you use Mina.
Miina Frame composition
In the module chain in the diagram, Ioservice is the application's entry, which is equivalent to the Ioaccepter,ioaccepter in the previous code is an extension interface of Ioservice. The Ioservice interface can be used to add multiple IoFilter that conform to the responsible chain pattern and are called by the ioprocessor thread. Ioaccepter, on the Ioservice interface, also provides interfaces that bind a communication port and unbind it.
Ioacceptor acceptor = new Socketacceptor ();
The above code, equivalent to the use of Socket communication as a service access, the current version of MINA also provides data-based message communication in addition to Socketaccepter Datagramaccepter and pipeline-based communication vmpipeaccepter. In addition, the serial communication access method is also included, and the current access mode based on serial communication has been provided in the MINA of the latest beta version. You can also implement your own Ioservice interface to use your own communication methods.
In the right-hand side of the Iohandler, this is the business processing module. There is no need to care about the actual communication details in the business processing class, just handle the information transmitted by the client. Writing the Handler class is the center of gravity for developing Web applications using MINA, which is equivalent to MINA has helped you with all the details of the communication. To simplify the Handler class, MINA provides the Iohandleradapter class, which simply implements the Iohandler interface, but does not do any processing.
A Iohandler interface has some of the following methods (from the API documentation for MINA):
- void Exceptioncaught (iosession session, Throwable cause)
Triggers this method when another method in the interface throws an exception that is not caught
- void Messagereceived (iosession session, Object message)
Triggers this method when the client's request information is received
- void Messagesent (iosession session , Object message)
Triggers this method when the information has been passed to the client
- void sessionclosed (iosession session)
When the connection is closed, such as when the client program quits unexpectedly, and so on
- void Sessioncreated (iosession session)
Triggers this method after a new client is connected
- void Sessionidle (iosession session, Idlestatus status)
Triggers this method when the connection is idle
- void sessionopened (iosession session)
Triggers this method when the connection is opened, typically with Sessioncreated will be triggered at the same time
We mentioned earlier that Ioservice is responsible for the underlying communications access, while Iohandler is responsible for business processing. So what is the use of IoFilter in the MINA architecture diagram? The answer is that you can use whatever you want. But one use is necessary, and that is the bridge between Ioservice and Iohandler. The most important method in the Iohandler interface is messagereceived, the second parameter of this method is an object-type message, and it is well known that object is the basis of all Java objects, so who decides exactly what type of message it is? The answer is in this IoFilter. In the previous example, we added a IoFilter is the new Protocolcodecfilter (New Textlinecodecfactory ()), the function of this filter is to convert the information from the client input into a line of text after passing to Iohandler, so we can cast the MSG object directly into a String object in messagereceived.
And if we don't provide any filters, then the second parameter type in the Messagereceived method is a byte buffer, and the corresponding class is Org.apache.mina.core.buffer.IoBuffer. Although you can also put the parsing client information in Iohandler to do, but this is not recommended practice, so that the original clear model and blurred, become iohandler not only business processing, but also to act as a protocol resolution task.
Mina itself comes with some commonly used filters, such as loggingfilter (logging), Blacklistfilter (blacklist filtering), Compressionfilter (compression), Sslfilter (SSL encryption), and so on.
In short, it is divided into three layers:
- I/O Service: Responsible for handling I/O.
- I/O Filter Chain: Responsible for encoding processing, byte to data structure or data structure to byte conversion, that is, the operation of non-business logic.
- I/O Handle: Responsible for handling business logic.
Client-side Communication process:
- Establish a connection with the server side via Socketconnector.
- After the link is established, I/O reads and writes to the I/O processor thread, and I/O processor is multithreaded.
- The data read through the I/O processor is filtered through all the configured iofilter,iofilter in the Iofilterchain, and the format is converted, and some custom protocols can be developed at this level.
- Finally iofilter the data to handler for business processing, complete the entire reading process.
- The writing process is similar, just upside down, write the data through Iosession.write, and then handler to write the business processing, the processing is completed to Iofilterchain, the message filtering and protocol conversion, and finally through the I/O Processor writes the data to the socket channel.
Iofilterchain as a message filter chain
- Reading is the process of moving from a low-level protocol to a high-level protocol, typically from a byte byte to a business object.
- Writing is typically a process from a business object to a byte of bytes.
The client communication process iosession throughout the entire communication process
Creating a server
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 {//define listening port private static Final int PORT = 6488; public static void Main (string[] args) throws IOException {//Create server-side monitoring thread ioacceptor acceptor = new Niosocket Acceptor (); Acceptor.getsessionconfig (). Setreadbuffersize (2048); Acceptor.getsessionconfig (). Setidletime (Idlestatus.both_idle, 10); Set the Logger Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ()); Set the encoding filter Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlineco DeCFactory (Charset.forname ("UTF-8"))); Specifies the business logic processor Acceptor.sethandler (new Timeserverhandler ()); Set the port number Acceptor.bind (new inetsocketaddress (port)); Start the Listener thread acceptor.bind (); }}
Import Org.apache.mina.core.service.iohandleradapter;import Org.apache.mina.core.session.idlestatus;import org.apache.mina.core.session.iosession;/** * Server-side business logic */public class Timeserverhandler extends Iohandleradapter {/** * Connection Creation Event */@Override public void sessioncreated (iosession session) {//Displays the IP and port System.out of the client. println (Session.getremoteaddress (). toString ()); } @Override public void Exceptioncaught (iosession session, Throwable cause) throws Exception {Cause.prin Tstacktrace (); /** * Message Receive event */@Override public void Messagereceived (iosession session, Object message) throws Exc eption {String STRMSG = message.tostring (); if (Strmsg.trim (). Equalsignorecase ("quit")) {Session.close (true); Return }//Return message string Session.write ("Hi client!"); Print the message content from the client System.out.println ("message written:" + STRMSG); } @Override public void sesSionidle (iosession session, Idlestatus status) throws Exception {System.out.println ("IDLE" + session.getidlecount ( status)); } }
Client
Import Java.net.inetsocketaddress;import Java.nio.charset.charset;import Org.apache.mina.core.future.connectfuture;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.niosocketconnector;public class Minatimeclient {public static void Mai N (string[] args) {//Create client connector. Niosocketconnector connector = new Niosocketconnector (); Connector.getfilterchain (). AddLast ("Logger", New Loggingfilter ()); Connector.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory (Charset.forna Me ("UTF-8"))); Set the connection timeout check time connector.setconnecttimeoutcheckinterval (30); Connector.sethandler (New Timeclienthandler ()); Establish the connection Connectfuture CF = Connector.connect (new inetsocketaddress ("192.168.2.109", 6488)); Wait for connection creation to complete Cf.awaituninterruptibly (); Cf.getsession (). Write ("Hi server!"); Cf.getsession (). Write ("Quit"); Wait for the connection to disconnect Cf.getsession (). Getclosefuture (). awaituninterruptibly (); Release the connection connector.dispose (); }}
Import Org.apache.mina.core.service.iohandleradapter;import Org.apache.mina.core.session.iosession;public class Timeclienthandler extends Iohandleradapter {public void messagereceived (iosession session, Object message) throws Exception { String content = message.tostring (); SYSTEM.OUT.PRINTLN ("Client receive a message is:" + content); } public void Messagesent (iosession session, Object message) throws Exception { System.out.println ("Messagesent- : "+ message); } }
http://my.oschina.net/ielts0909/blog?catalog=253154
Http://www.blogjava.net/mikechen/archive/2012/03/15/371938.html
http://dxf1122.blog.163.com/blog/static/54041004200931371414356/
Http://blog.sina.com.cn/s/blog_7abc61de0100sdoi.html
Http://mina.apache.org/mina-project/documentation.html
Http://wenku.baidu.com/view/b9af67c34028915f804dc292.html
Http://wenku.baidu.com/view/46800bce0508763231121232.html
Http://wenku.baidu.com/view/5ccc7935b90d6c85ec3ac6e7.html
Apache Mina (i)