MINA Notes


About mina :
     Similar to netty, java's network layer IO processing framework provides a high-concurrency network programming framework.
Example
reference:      Getting started example: org.apache.mina.example.gettingstarted.timeserver.MinaTimeServer telnet server example.
  TCP Example: org.apache.mina.example.sumup.Server/Client Numerical
  UDP Example: org.apache.mina.example.udp.MemoryMonitor/cient


Advanced Features:
     IoService: Base class for all IO services, whether on the server is still on the client side. It will handle all interactions with your application, as well as with remote peers, sending and receiving messages, managing sessions, managing connections, and more. It is an interface, the server is implemented as IoAcceptor, and the client is IoConnector
            1. Session management: create and delete sessions, detect idle sessions
            2. Filter chain management: manipulate the filter chain, allowing users to change the filter chain in operation
            3 .Handler call: call a handler when a new message is received, etc.
            4. Statistics management: update the number of messages sent, the number of bytes sent, etc.
            5. Listener management: manage user-created listeners
            6. Communication Management: processing the transmitted data on the server side and on the server side
            7. The two most important implementations are IoAcceptor IoConnector

     IoAcceptor : The IoAcceptor interface is named because of the accept() method and is used for server coding. Common implementation classes
            1.NioSocketAcceptor: non-blocking socket transmission IoAcceptor
            2.NioDatagramAcceptor: non- blocking Blocking UDP transmission IoAcceptor
            3.AprSocketAcceptor: APR-based blocking socket transmission IoAcceptor
            4.VmPipeSocketAcceptor: in-VM IoAcceptor

     IoConnector : Client coding implementation, because socket often uses the connect method to link the server
            1.NioSocketConnector: non-blocking socket Word transport IoConnector
            2.NioDatagramConnector: Non-blocking UDP transport IoConnector
            3: AprSocketConnector: APR-based blocking socket transport IoConnector
            4.ProxyConnector: An IoConnector providing proxy support 5.SerialConnector: An IoConnector
            for serial transport
            6.VmPipeConnector: in-VM IoConnector
    

Session : Session (session) is the core of MINA. Every time a client connects to the server, a new session is created and kept in memory until the client closes the connection. Therefore, it can be used as state maintenance to solve many stateless problems.
     Status:
            1.connected: the session has been created and available
            2.idle: the session has not processed any requests for at least a period of time (this period is configurable)
            3.closing: the session is closing (and there are messages being cleared) , the cleanup is not over)
            4.closed: The session has now been closed, and there is no other way to bring it back
     : custom attributes, the session is used to hold persistent information about the connection, and during request processing, during the lifetime of the session, the server any information that may be required.
            int counterValue = session.getAttribute( "counter" );
            session.setAttribute( "counter", counterValue + 1 );

           
Filter : Filter: filter all I/O events and requests between IoService and IoHandler,
     commonly used filter
            1 .LoggingFilter logs all events and requests
                   MINA uses Simple Logging Facade for Java (SLF4J), SLF4J selects the appropriate JAR package, the following log framework | required jar
                         1.Log4J 1.2.x | slf4j-api.jar, slf4j-log4j12.jar**
                         2. Log4J 1.3.x | slf4j-api.jar, slf4j-log4j13.jar
                         3.java.util.logging | slf4j-api.jar, slf4j-jdk14.jar**
                         4.Commons Logging | slf4j-api.jar, slf4j- jcl.jar
            2.ProtocolCodecFilter converts a connected ByteBuffer into a message POJO, and vice versa
                   Why do you need a codec filter?
                         1 If there is no ProtocolCodecFilter, a call to IoSession.write(Object message) by the sender will result in messageReceived(IoSession session, Object message) events of multiple receivers, and multiple calls of IoSession.write(Object message) will only Raises only one messageReceived event.
                         2 Most web applications need a way to find out where the current message ends and the next message starts
                         3 It is possible to implement all this logic in your IoHandler, but adding a ProtocolCodecFilter can make your code cleaner and Easy to maintain
                         4 It separates your protocol logic from your business logic (IoHandler)
                   How to use it?
                         1. Use a fixed-length byte encoding
                         2. Use a fixed-length header to indicate the length of the body
                         3. Use a delimiter. For example, many text-based protocols 3.CompressionFilter
                        
            compresses all data in each message
            4.SSLFilter adds SSL-TLS-StartTLS support
     overriding:
            public class MyFilter extends IoFilterAdapter {
              @Override
              public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception
              on {
              // Some logic here...
              nextFilter.sessionOpened(session);
              // Some other logic here...
              }
              }
    

IOHandler : IO handler, each session will be attached to a handler, which is responsible for scheduling to Your app's message. This handler will also send response packets by using the session, just call the write() method: for example session.write( <your message> );
     common methods:
            1.sessionCreated: The session establishment event is triggered when a new connection is created , for TCP this is the result of a connection acceptance, and for UDP this is generated when a UDP packet is received. This method can be used to initialize session attributes and perform one-time activities for some specific connection.
            2.sessionOpened: The session open event is called when a connection is opened, it is always called after the sessionCreated event. If a threading model is configured, this method will be called in a thread other than the I/O processing thread.
            3.sessionClosed: The session close event is called when the session is closed. Session cleanup activities such as clearing payment information can be performed here.
            4.sessionIdle: The session idle time is triggered when the session becomes idle. This method is not called for UDP-based transports
            5.exceptionCaught: This method is called when user code or MINA throws an exception. The link will be closed
            6.messageReceived: The message received event fires when a message is received. This is the most common processing of an application. 7.messageSent: The message sending event triggers the IoBuffer
            when the message response is sent (calling IoSession.write())      A byte buffer used by the MINA application. It is used in place of ByteBuffer. MINA does not directly use NIO's ByteBuffer      operations:             1.IoBuffer is an abstract class, so it cannot be instantiated directly. To allocate an IoBuffer, we need to use one of the two allocate() methods.             1.1 public static IoBuffer allocate(int capacity, boolean direct) and             1.2 public static IoBuffer allocate(int capacity) server application : service creation and destruction             1. Create,, new IOAcceptor             2. Destroy,, acceptor.dispose();// The default service can only be set to true to execute immediately after all waiting sessions have been processed








           






    



            3. IoService state-related functions: isActive(), isDisposing(), isDisposed()
            4. Manage IoHandler: After the service is instantiated, you can add or get the IoHandler associated with it. You just need to call a setHandler(IoHandler) or getHandler() method.
            5. Manage filter chain: acceptor.getFilterChain().addLast("logger", new LoggingFilter())
     Client application:
            1. Implement an implementation of IoConnector interface
            2. Other process reference service application


APR application:
     APR (Apache Portable Runtime) provides better scalability, performance, and better integration with local server technology. MINA transmits APR as usual. Current
  application: IoAcceptor acceptor = new NioSocketAcceptor(); changed to IoAcceptor acceptor = new AprSocketAcceptor();


Serial application:
     With MINA 2.0 you can connect to a serial port just as you would with MINA to a TCP/IP
            port Use mina-transport-serial and just put the appropriate .dll or .so in the jre/lib/i386/ directory of your JDK/JRE
     Application example:
            1. You need a SerialConnector to connect to a serial port:, nothing different except SocketConnector
             // create your connector
             IoConnector connector = new SerialConnector()
             connector.setHandler( ... here your buisness logic IoHandler ... );
            2. Create serial address
                   SerialAddress portAddress=new SerialAddress( "/dev/ttyS0", 38400, 8, StopBits.BITS_1,Parity.NONE, FlowControl.NONE );//The first parameter is your port logo. For Windows computers, the serial ports are called "COM1", "COM2", etc... For Linux and other Unix systems: "/dev/ttyS0", "/dev/ttyS1", "/dev/ttyUSB0" .
            3., connect the connector to the corresponding address
                   ConnectFuture future = connector.connect( portAddress );
                   future.await();
                   IoSession sessin = future.getSession();








Code example: Refer to


Server for details:
       private static final Logger logger =Logger.getLogger(Server.class);
    private static final int SERVER_PORT = 8080;
    // 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 {
        NioSocketAcceptor acceptor = new NioSocketAcceptor(); //Create an IOservice which is a receiver
        // Prepare the service configuration.
        if (USE_CUSTOM_CODEC) { //添加filter-chains
            acceptor.getFilterChain()
                    .addLast(
                            "codec",
                            new ProtocolCodecFilter(
                                    new SumUpProtocolCodecFactory(true)));
        } else {
            acceptor.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(
                            new ObjectSerializationCodecFactory()));
        }
        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.setHandler(new ServerSessionHandler()); //Server IO handler
        acceptor.bind(new InetSocketAddress(SERVER_PORT)); //Binding, asynchronous
        System.out.println("Listening on port " + SERVER_PORT);
        logger.error("the service ok !!!");
    }



If you need UDP service, you only need to modify the IOAcceptor code.
For example :
       
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();//Create a Datagrame receiver
        acceptor.setHandler(new MemoryMonitorHandler(this));//Add IOhandler, an IoHandler to handle events generated by the MINA framework
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        chain.addLast("logger", new LoggingFilter());//Add log filter
        DatagramSessionConfig dcfg = acceptor.getSessionConfig();//添加session配置
        dcfg.setReuseAddress(true);//Configuration, address reuse Next, let's look at some more specific UDP transmission codes. We set the acceptor to




Client:
       
//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];
        int [] values = new int[]{1,2,3,5};
        for (int i = 0; i < args.length; i++) {
            values[i] = Integer.parseInt(args[i]);
        }
        NioSocketConnector connector = new NioSocketConnector();//Create a connector is not an acceptor We have created a NIO Socket connector
        // Configure the service.
        connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
        if (USE_CUSTOM_CODEC) {
            connector.getFilterChain().addLast( //Create a filter-chains
                    "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)); //Create an IOHandler and add it to the connector;; here we create an instance of ClientSessionHandler and set it as the Connector's handler
        IoSession session;
        for (;;) {
            try {
                ConnectFuture future = connector.connect(new InetSocketAddress(
                        HOSTNAME, PORT));//This is the most important part. We will connect to the remote server. Because it is an asynchronous connection task, we use
                //ConnectFuture to know when the connection is complete. Once the connection is complete, we will get the associated IoSession. to
               // Any message sent by the server, we have to write to the session. All responses or messages from the server will pass through
               // Filter chain and finally handled by IoHandler.
                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
       
        for(int i = 0;i<5;i++){
            AddMessage m = new AddMessage();
            m.setSequence(i);
            m.setValue( i+6 );
// WriteFuture wf =session.write( i+6 ); // Send an error code, there will be an exception, but no error will be reported, failure
              WriteFuture wf  =session.write(m); // 发送
              wf.addListener(new IoFutureListener<IoFuture>() {
                           public void operationComplete(IoFuture future) {
                                  // TODO Auto-generated method stub
                                  System.out.println("send ok +" );
                                  //+future.getSession().write("hell")
                           }
                     });
        }
       
       
        session.getCloseFuture().awaitUninterruptibly();//Call the session close command,
       
        connector.dispose();//Disconnect

  

UDP client:

      
LOGGER.debug("UDPClient::UDPClient");
        LOGGER.debug("Created a datagram connector");
        connector = new NioDatagramConnector();//connector Clients create a NioDatagramConnector, set up the handler and connect to the server.
        LOGGER.debug("Setting the handler");
        connector.setHandler(this);
        LOGGER.debug("About to connect to the server...");
        ConnectFuture connFuture = connector.connect(new InetSocketAddress( //Link to the specified server
                "localhost", MemoryMonitor.PORT));
        LOGGER.debug("About to wait.");
        connFuture.awaitUninterruptibly();//conect is asynchronous, where the synchronization waits for the completion of the connection
        LOGGER.debug("Adding a future listener.");
        connFuture.addListener(new IoFutureListener<ConnectFuture>() { //Once we know that we have established a connection, we can start writing data to the server:
            public void operationComplete(ConnectFuture future) {
                if (future.isConnected()) {
                    LOGGER.debug("...connected");
                    session = future.getSession();
                    try {
                        sendData();//30s send data
                    } catch (InterruptedException e) {
                        e.printStackTrace ();
                    }
                } else {
                    LOGGER.error("Not connected...exiting");
                }
            }
        });

  
Aside from the independent business, the code interface is unified, and only the appropriate implementation class can be selected.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326487065&siteId=291194637