Rapid development of network applications based on the Mina framework

Source: Internet
Author: User

1. Introduction to the Mina framework
Mina (Multipurpose infrastructure for network applications) is used to develop high-performance and high-availability network applications.Program. By using the Mina framework, you can save on complex tasks such as underlying I/O and thread concurrency. developers can devote more energy to business design and development. Mina framework is widely used. Open-source projects include Apache directory, asyncweb, Apache qpid, quickfix/J, openfire, subethastmp, and red5. The stable version of the Mina framework is 1.1.6, and the latest version 2.0 has released the M1 version.
The Mina framework is developed based on the Java NiO class library. It adopts non-blocking asynchronous transmission, event-driven, batch data transmission, and TCP and UDP protocols; design Mode of control reversal (spring supported); elegant loose coupling architecture; Flexible Loading filter mechanism; easier implementation of unit testing; number of customizable threads, in order to improve the performance of running on the multi-processor; using callback to complete the call, the thread is easier to use.

2. Common classes of the Mina framework
The class niosocketacceptor is used to create server listening;
Class niosocketconnector is used to create client connections;
Iosession is used to save session properties and send messages;
Iohandleradapter is used to define business logic. Common methods include:
Method Definition
Sessioncreated () is triggered when a session is created.
Sessionopened () is triggered when the session starts.
Sessionclosed () is triggered when the session is closed
Sessionidle () is triggered when the session is idle
Exceptioncaught () This method is triggered when exceptions thrown by other methods in the interface are not captured.
Messagerecieved () is triggered when a message is received.
Messagesent () is triggered when a message is sent.

3. server application development example
The following describes how to use the Mina framework for development based on the mina2.0m1 version. Development Environment for jdk6.0, development tools netbeans6.0, the jar package slf4j-api.jar, slf4j-jdk14.jar, MINA-core-2.0.0-M1.jar.
First, define a business logic processor timeserverhandler that inherits from iohandleradapter and implements the following functions: when the client creates a session, the IP address and port of the client device are displayed; when the client inputs quit, the session ends; when the client inputs other content, the current time is sent to the client. Code As follows:
Public class timeserverhandler extends iohandleradapter
{
@ Override
Public void sessioncreated (iosession session ){
// Display the Client IP address and port
System. Out. println (session. getremoteaddress (). tostring ());
}
@ Override
Public void messagereceived (iosession session, object message) throws exception
{
String STR = message. tostring ();
If (Str. Trim (). inclusignorecase ("quit ")){
Session. Close (); // end the session
Return;
}
Date = new date ();
Session. Write (date. tostring (); // returns the string of the current time
System. Out. println ("message written ...");
}
}
Define a minatimeserver class to start the server:
Public class minatimeserver
{
Private Static final int Port = 9123; // defines the listening port
Public static void main (string [] ARGs) throws ioexception
{
Ioacceptor acceptor = new niosocketacceptor ();
Acceptor. getfilterchain (). addlast ("logger", new loggingfilter ());
Acceptor. getfilterchain (). addlast ("codec", new protocolcodecfilter (New textlinecodecfactory (charset. forname ("UTF-8"); // specify the encoding filter
Acceptor. sethandler (New timeserverhandler (); // specifies the business logic processor.
Acceptor. setdefalocallocaladdress (New inetsocketaddress (port); // you can specify the port number.
Acceptor. BIND (); // start the listener
}
}

4. Test
First, run minatimeserver, start the server, and then run "Telnet 127.0.0.1 9123" on the command line to log on. The server output is as follows:
16:15:29 org. Apache. Mina. Filter. Logging. loglevel $4 log
/10.64.2.133: 4140 IP address and port number
Information: created
16:15:29 org. Apache. Mina. Filter. Logging. loglevel $4 log
Information: opened press enter on the client. on the client side, you can see that the server returns the current time:
Thu Feb 21 16:20:14 CST 2008
Server output:
16:20:14 org. Apache. Mina. Filter. Logging. loglevel $4 log
Information: received ed: heapbuffer [Pos = 0 Lim = 2 CAP = 2048: 0d 0a] receives a carriage return.
Message written...
16:20:14 org. Apache. Mina. Filter. Logging. loglevel $4 log
Information: Sent: heapbuffer [Pos = 0 Lim = 29 Cap = 30: 54 68 75 20 46 65 62 20 32 31 20 31 36 3A 32 30...]
16:20:14 org. Apache. Mina. Filter. Logging. loglevel $4 log
Information: Sent: heapbuffer [Pos = 0 Lim = 0 Cap = 0: Empty] 5. Client development example
First, define the class timeclienthandler to process the message receiving event:
Class timeclienthandler extends iohandleradapter {
Public timeclienthandler (){
}
@ Override
Public void messagereceived (iosession session, object message) throws exception {
System. Out. println (Message); // displays the received message.
}
}
Then define the minatimeclient class to connect to the server and send messages to the server:
Public class minatimeclient {
Public static void main (string [] ARGs ){
// Create a client connector.
Nictor etconnector conne= new niosocketconnector ();
Connector ". getfilterchain (). addlast (" logger ", new loggingfilter ());
Connector. getfilterchain (). addlast ("codec", new protocolcodecfilter (New textlinecodecfactory (charset. forname ("UTF-8"); // sets the encoding filter
Connector. setconnecttimeout (30 );
Connector. sethandler (New timeclienthandler (); // sets the event processor.
Connectfuture cf = connector. Connect (
New inetsocketaddress ("127.0.0.1", 9123); // establish a connection
CF/awaituninterruptibly (); // wait until the connection is created
Cf. getsession (). Write ("hello"); // send a message
Cf. getsession (). Write ("quit"); // send a message
Cf. getsession (). getclosefuture (). awaituninterruptibly (); // wait for the connection to be disconnected
Connector. Dispose ();
}
}
6. Summary
The preceding example shows that the code structure of network applications developed using the Mina framework is clearer, and the Mina framework completes the underlying thread management; the built-in encoder of Mina can meet the needs of most users, eliminating the need for developers to decode messages. It is said that the performance of the Mina server program has approached the network service developed in C/C ++ language. Therefore, we recommend that you use the Mina framework during network application development to improve our development efficiency and application execution efficiency.

 

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.