ApacheMina study notes (2)-basics

Source: Internet
Author: User
In Chapter 1, we have a general understanding of MINA. in this chapter, we will make a detailed analysis of the client server model in MINA. Some examples based on TCP and UDP are also provided. In Chapter 1, we have a general understanding of MINA. in this chapter, we will make a detailed analysis of the client/server model in MINA. Some examples based on TCP and UDP are also provided.

Application Structure

Server structure
Client structure

Simple TCP server
Simple TCP client
Simple UDP server
Simple UDP client

Summary Application Structure

The application structure using the MINA framework is as follows:

After the preparation is complete, we start to write the code.

import java.net.InetSocketAddress;  import org.apache.mina.core.service.IoAcceptor;  import org.apache.mina.transport.socket.nio.NioSocketAcceptor;    public class MinaTimeServer  {      private static final int PORT = 9123;      public static void main( String[] args ) throws IOException      {          IoAcceptor acceptor = new NioSocketAcceptor();          acceptor.bind( new InetSocketAddress(PORT) );      }  }

Next, we will add the filter chain configuration in the above code.

Import java. io. IOException; import java.net. inetSocketAddress; import java. nio. charset. charset; import org. apache. mina. core. service. ioAcceptor; 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 {public static void main (String [] args) {IoAcceptor acceptor = new NioSocketAcceptor (); acceptor. getFilterChain (). addLast ("logger", new LoggingFilter (); // All log information acceptor will be created here. getFilterChain (). addLast ("codec", new ProtocolCodecFilter (new TextLineCodecFactory (Charset. forName ("UTF-8"); // The second filter is used to pass the data acceptor. bind (new InetSocketAddress (PORT ));}}

Next, we need to define the Handler used to process messages. This Handler class must implement the IoHandler interface. In MINA, this Handler is the key to program development. in this teaching, we will inherit from IoHandlerAdapter.

import java.util.Date;  import org.apache.mina.core.session.IdleStatus;  import org.apache.mina.core.service.IoHandlerAdapter;  import org.apache.mina.core.session.IoSession;    public class TimeServerHandler extends IoHandlerAdapter  {      @Override      public void exceptionCaught( IoSession session, Throwable cause ) throws Exception      {          cause.printStackTrace();      }      @Override      public void messageReceived( IoSession session, Object message ) throws Exception      {          String str = message.toString();          if( str.trim().equalsIgnoreCase("quit") ) {              session.close();              return;          }          Date date = new Date();          session.write( date.toString() );          System.out.println("Message written...");      }      @Override      public void sessionIdle( IoSession session, IdleStatus status ) throws Exception      {          System.out.println( "IDLE " + session.getIdleCount( status ));      }  }

Finally, the complete server code is as follows:

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 = 9123; 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"); acceptor. setHandler (new TimeServerHandler (); // Set Handler acceptor here. getSessionConfig (). setReadBufferSize (2048); // This is to set the ssesion buffer acceptor. getSessionConfig (). setIdleTime (IdleStatus. BOTH_IDLE, 10); acceptor. bind (new InetSocketAddress (PORT ));}}

Run the server and enter the command telnet 127.0.0.1 9123 on the terminal. when you enter any character other than "quit", the server returns the current time to the terminal.

Simple TCP client

import java.net.InetSocketAddress;  import org.apache.mina.core.RuntimeIoException;  import org.apache.mina.core.future.ConnectFuture;  import org.apache.mina.core.session.IoSession;  import org.apache.mina.example.sumup.codec.SumUpProtocolCodecFactory;  import org.apache.mina.filter.codec.ProtocolCodecFilter;  import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;  import org.apache.mina.filter.logging.LoggingFilter;  import org.apache.mina.transport.socket.nio.NioSocketConnector;       /**    * (Entry Point) Starts SumUp client.    *    * @author Apache MINA Project    */    public class Client {       private static final String HOSTNAME = "localhost";            private static final int PORT = 8080;           private static final long CONNECT_TIMEOUT = 30*1000L; // 30 seconds            // Set this to false to use object serialization instead of custom codec.        private static final boolean USE_CUSTOM_CODEC = true;            public static void main(String[] args) throws Throwable {            if (args.length == 0) {                System.out.println("Please specify the list of any integers");                return;            }                // prepare values to sum up           int[] values = new int[args.length];            for (int i = 0; i < args.length; i++) {                values[i] = Integer.parseInt(args[i]);            }                NioSocketConnector connector = new NioSocketConnector();                // Configure the service.            connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);            if (USE_CUSTOM_CODEC) {
connector.getFilterChain().addLast(                        "codec",                        new ProtocolCodecFilter(                                new SumUpProtocolCodecFactory(false)));            } else {                connector.getFilterChain().addLast(                        "codec",                        new ProtocolCodecFilter(                                new ObjectSerializationCodecFactory()));            }            connector.getFilterChain().addLast("logger", new LoggingFilter());                connector.setHandler(new ClientSessionHandler(values));                IoSession session;            for (;;) {                try {                    ConnectFuture future = connector.connect(new InetSocketAddress(                            HOSTNAME, PORT));                    future.awaitUninterruptibly();                    session = future.getSession();                    break;               } catch (RuntimeIoException e) {                    System.err.println("Failed to connect.");                    e.printStackTrace();                    Thread.sleep(5000);                }            }                // wait until the summation is done           session.getCloseFuture().awaitUninterruptibly();                        connector.dispose();        }    }

If you do not need to write the UDP example, go to the Apache official website.

Http://mina.apache.org/mina-project/userguide/ch2-basics/sample-udp-client.html

The above is the basic content of Apache Mina study notes (2). For more information, see PHP Chinese website (www.php1.cn )!

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.