Rapid development of Web applications based on Mina framework

Source: Internet
Author: User

1. Introduction to the Mina framework
MINA (Multipurpose Infrastructure for network applications) is the foundation framework for developing high-performance and high-availability Web applications. By using the Mina framework, you can save on complex tasks such as underlying I/O and thread concurrency, and developers can devote more effort to business design and development. Mina framework is widely used, open source projects are Apache Directory, Asyncweb, Apache Qpid, quickfix/j, OpenFire, subethastmp, Red5 and so on. The current stable version of the Mina framework is 1.1.6, and the latest version of 2.0 is now available in the M1 release.
Mina Framework features: Based on Java NIO Library development, non-blocking asynchronous transmission, event-driven, support for bulk data transmission, support TCP, UDP protocol, control inversion design mode (support Spring), adopt elegant loosely coupled architecture, flexible loading filter mechanism ; Unit tests are easier to implement; You can customize the number of threads to improve performance on multiple processors, and invoke callbacks to make the thread easier to use.

2. Common classes of the Mina framework
Class Niosocketacceptor is used to create server-side monitoring;
Class Niosocketconnector is used to create client connections;
Class iosession is used to save session properties and send messages;
Class Iohandleradapter are used to define business logic and are commonly used in the following ways:
Method definition
Sessioncreated () is triggered when the 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 () Triggers this method when another method in the interface throws an exception that is not caught
Messagerecieved () triggered when a message is received
Messagesent () is triggered when a message is sent

3. Server-side application development examples
The following will be based on the MINA2.0M1 version, using an example to demonstrate how to use the Mina framework for development. Development environment for jdk6.0, development tools NetBeans6.0, required jar package Slf4j-api.jar, Slf4j-jdk14.jar, Mina-core-2.0.0-m1.jar.
First, define a business logic processor Timeserverhandler, inherited from the iohandleradapter, the implementation of the function is: When the client creates the session will display the client device IP and port; End the session when the client enters quit When the client enters other content, the current time is sent to the client. The code is as follows:

 Public classTimeserverhandler extends Iohandleradapter {@Override Public voidSessioncreated (iosession session) {//displaying the IP and port of the clientSystem. out. println (Session.getremoteaddress (). toString ()); @Override Public voidMessagereceived (iosession session, Object message) throws Exception {String str=message.tostring ();if(Str.trim (). Equalsignorecase ("quit") ) {session.close ();//End Sessionreturn; } Date Date=NewDate (); Session.write (date.tostring ());//string that returns the current timeSystem. out. println ("Message Written ..."); }} and define a class Minatimeserver to start the server: Public classMinatimeserver {Private StaticFinalintPORT =9123;//defining a listening port Public Static voidMain (string[] args) throws IOException {Ioacceptor acceptor=Newniosocketacceptor (); Acceptor.getfilterchain (). AddLast ("Logger",NewLoggingfilter ()); Acceptor.getfilterchain (). AddLast ("codec",NewProtocolcodecfilter (NewTextlinecodecfactory (Charset.forname ("UTF-8"))));//specifying the encoding filterAcceptor.sethandler (NewTimeserverhandler ());//specifying the business logic processorAcceptor.setdefaultlocaladdress (NewInetsocketaddress (PORT));//set the port numberAcceptor.bind ();//Start Monitoring} } 

4. Test
Run Minatimeserver First, start the server, and then run "telnet 127.0.0.1 9123" on the command line to log in, and you will see the server output as follows:
2008-2-21 16:15:29 org.apache.mina.filter.logging.loglevel$4 Log
/10.64.2.137:4140? IP and port number
Information: CREATED
2008-2-21 16:15:29 org.apache.mina.filter.logging.loglevel$4 Log
Info: Opened in the client input enter, the client can see the server return the current time:
Thu Feb 16:20:14 CST 2008
Service-Side output:
2008-2-21 16:20:14 org.apache.mina.filter.logging.loglevel$4 Log
Info: received:heapbuffer[pos=0 lim=2 cap=2048:0d 0A]? receive a carriage return
Message written ...
2008-2-21 16:20:14 org.apache.mina.filter.logging.loglevel$4 Log
Info: sent:heapbuffer[pos=0 lim=29 cap=30:54-3 A 32 30 ...] [More]
2008-2-21 16:20:14 org.apache.mina.filter.logging.loglevel$4 Log
Info: sent:heapbuffer[pos=0 lim=0 cap=0:empty] 5. Client Development Examples
The class Timeclienthandler is first defined to handle the message receive event:

classTimeclienthandler extends iohandleradapter{ PublicTimeclienthandler () {} @Override Public voidMessagereceived (iosession session, Object message) throws Exception {System. out. println (message);//Show received Messages}} Then define the Minatimeclient class to connect to the server and send a message to the server: Public classminatimeclient { Public Static voidMain (string[] args) {//Create a client connector.Niosocketconnector connector =Newniosocketconnector (); Connector.getfilterchain (). AddLast ("Logger",NewLoggingfilter ()); Connector.getfilterchain (). AddLast ("codec",NewProtocolcodecfilter (NewTextlinecodecfactory (Charset.forname ("UTF-8"))));//set up the encoding filterConnector.setconnecttimeout ( -); Connector.sethandler (NewTimeclienthandler ());//setting up event handlersConnectfuture CF =Connector.connect (NewInetsocketaddress ("127.0.0.1",9123));//Establish a connectionCf.awaituninterruptibly ();//Wait for connection creation to completeCf.getsession (). Write ("Hello");//Send MessageCf.getsession (). Write ("quit");//Send MessageCf.getsession (). Getclosefuture (). awaituninterruptibly ();//wait for the connection to breakconnector.dispose ();} } 

6. Summarize
As you can see from the example above, the structure of the network application code developed using the Mina framework is clearer, the Mina framework completes the underlying thread management, and the Mina built-in encoder can meet the needs of most users, eliminating the need for developer message encoding and decoding. The performance of the Mina Development Server program has been approximated by the use of a network service developed in the C + + language. Therefore, it is recommended that you try to use the Mina framework during the development of your Web application to improve our development efficiency and application execution efficiency.

Rapid development of Web applications based on Mina framework

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.