Integration of MINA Framework with tomcat

Posted by Pioden on Thu, 16 Apr 2020 18:05:14 +0200

In the previous article, we mainly discussed how the mina framework is used in the main function, but in practice, many web projects are started through tomcat, so it is necessary to integrate the mina framework into tomcat.This article focuses on how mina can be started in tomcat. The framework used by the web is the Spring + SpringMvc + Mybatis framework.
Starting MINA in tomcat is a three-step process:
1. Configure the startup listening class in web.xml, where XXX.MINAListener is a custom listening class that runs at service startup.XXX.MINAListener writes the class name of the full path.

<listener>
<listener-class>XXX.MiNaListener</listener-class>
<listener>

2. The MiNaListener class implements the ServletContextListener class by configuring the startup parameters of the MINA server in the contextInitialized method.

package test.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
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.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MiNaListener implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // 4Step operation
        //1 Newly build NioSocketAcceptor Instance object
        IoAcceptor acceptor = new NioSocketAcceptor();
        // 2.Set Read Cache Size
        acceptor.getSessionConfig().setReadBufferSize(2048);
        // Set response time, read and write channels are in10No action in seconds goes into idle state
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        // 3.Set Message Processing Object
        acceptor.setHandler(new MyServerHandler());
        // Set the character encoding format used
        acceptor.getFilterChain().addLast(
                "codec",
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                        .forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
                        LineDelimiter.WINDOWS.getValue())));
        // 4.Bind Port
        try {
            // Bind Port Open Service
            acceptor.bind(new InetSocketAddress(12345));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. Customize message processing classes to receive messages from clients.
Customize the MyServerHandler class to handle client-side messages.

package test.mina;

import java.util.Date;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Message Processing Class
 * @author Administrator
 */
public class MyServerHandler extends IoHandlerAdapter {

    private int count = 0;
    private final static Logger log = LoggerFactory .getLogger(MyServerHandler.class);

    // Whether or not to create a session is up to the bottom
    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
        System.out.println("New Customer Connection");
    }

    // Callback sessionOpened when session is created
    @Override
    public void sessionOpened(IoSession session) throws Exception {

        super.sessionOpened(session);
        count++;
        System.out.println("No. " + count + " individual client Land! address:  : " + session.getRemoteAddress());

        sessionWrite(session);
    }

    // Get a session connection to send messages to the client at any time
    private void sessionWrite(IoSession session) {
        session.write("Sent by Server1" + 1);
    }

    /**
     * This function is called back when a client sends a message
     */
    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {

        String str = message.toString();
        log.info("The message received is [" + str + "]");
        if (str.endsWith("quit")) {
            session.close(true);
            return;
        }
        System.out.println(str);
        String str1 = message.toString();
        Date date = new Date();
        session.write(date.toString());
        System.out.println("Received data:" + str1);
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
    }

    /**
     * session Called when closed
     */
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
    }

    /**
     * session Called when idle
     */
    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        super.sessionIdle(session, status);
    }

    /**
     * Called when exception is caught
     */
    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        super.exceptionCaught(session, cause);
    }

}

With the above steps, when tomcat is started, the corresponding mina framework is also started.But here are a few things to note:
1. The listening class configured in web.xml must be a full path class name
2. The port number configured in the MINA framework cannot be the same as that of tomcat
3. The client-side and server-side encoding formats of mina must be consistent, otherwise messages will not be received

Topics: Session Apache Tomcat Java