Mina network communication framework

Mina framework definition

The Mina framework is a network communication application framework open sourced by Apache and a Java NIO communication framework.

Mina framework function

The Mina framework is an encapsulation of the Java NIO package, which simplifies the difficulty of NIO program development and encapsulates many underlying details.

It mainly shields some details of network communication, such as encapsulating Socket, and is an implementation architecture of NIO, which can help us quickly develop network communication.

Mina framework architecture

1. Communication layer framework

MINA is a bridge between the application program (server and client) and the network layer (TCP UDP memory communication). Mina is located between the user application program and the underlying Java network API (and in-VM communication). We develop a network based on Mina application, you don't need to worry about complex communication details.

Detailed Explanation of Mina Framework (Definition of Function and Functional Architecture)-mikechen

2. The overall structure of the application

The bottom layer of Mina mainly relies on the Java NIO library, and the upper layer provides an event-based asynchronous interface. The Mina application framework is divided into three main components. The remote client establishes a connection through IoService to obtain a session, and the session transmits data to IoFilterChain Filter, and finally the client performs data operations in IoHandle. IoFilter acts as a bridge between IoService and IoHandler.

  • I/O Service, specifically the components that provide services.
  • I/O Filter Chain, filter chain, is responsible for encoding processing, byte-to-data structure or data structure-to-byte conversion, etc., that is, non-business logic operations;
  • I/O Handler, used to process user's business logic.

Detailed Explanation of Mina Framework (Definition of Function and Functional Architecture)-mikechen

Server/Client Architecture

The role of the server is to open the listening port, wait for the arrival of requests, process them, and send responses to the requests. At the same time, the server will create a session for each connection, and provide various precision services during the session period, such as when the connection is created (sessionCreated(IoSession session)), when the connection is waiting (sessionIdle(IoSession session, IdleStatus status)), when the connection When destroyed (sessionClosed(IoSession session)), etc. Mina's api provides consistent server-side operations for TCP/UDP.

  • The IOAcceptor listens for requests from the network.
  • When a new connection is established, a new session is created, which is used to provide services to clients of the same IP/port combination.
  • The data packet needs to pass through a series of filters, which can be used to modify the content of the data packet (such as converting objects, adding or modifying information, etc.), among which it is very useful to convert the original byte stream into a POJO object. Of course this requires support from the codec.
  • Finally, these data packets or transformed objects will be processed by IOHandler, and we will implement IOHandler to handle specific business logic.

The client executes the process. After the client receives all response requests and messages from the server through IoHandler, the developer traverses the filters added to the filter chain when connecting to the server through IoConnector, and then sends data to the server through IoConnector.

  • The client first creates an IOConnector and starts the binding with the Server
  • After the Connection is created, a Session will be created and associated with the Connection
  • The application/client writes the session, causing data to be sent to the server, after traversing the filter chain
  • All responses/messages received from the Server will traverse the filter chain and land on the IOHandler for processing

Detailed Explanation of Mina Framework (Definition of Function and Functional Architecture)-mikechen

Mina framework usage scenarios

Server-side asynchronous communication scenario: mina is an asynchronous communication framework, and the general use scenario is server-side development, long connection, and asynchronous communication use;

Game industry: If you want to use the Java language to develop game servers, then the Mina framework can be used as an option;

The MINA framework is widely used, and the open source projects used include Apache Directory, AsyncWeb, ApacheQpid, QuickFIX/J, Openfire, SubEthaSTMP, red5, etc.



Mina network communication framework

Since the traditional Socket network programming is based on the implementation of one thread corresponding to one client, a large number of thread creation and destruction lead to performance degradation and cannot cope with high concurrent access. Therefore, based on server-side network communication development, we often use the Mina network communication framework, namely Often said Java NIO (java non-blocking IO) development.

First, let's take a look at several important interfaces of Mina:

IoServiece :这个接口在一个线程上负责套接字的建立,拥有自己的 Selector,监听是否有连接被建立。
IoProcessor :这个接口在另一个线程上负责检查是否有数据在通道上读写,也就是说它也拥有自己的
 Selector,这是与我们使用 JAVA NIO 编码时的一个不同之处,通常在 JAVA NIO 编码中,我们都
 是使用一个 Selector,也就是不区分 IoServiceIoProcessor 两个功能接口。另外,IoProcessor 负责调用注册在 IoService 上的过滤器,并在过滤器链之后调用 IoHandlerIoAccepter :相当于网络应用程序中的服务器端
IoConnector :相当于客户端
IoSession :当前客户端到服务器端的一个连接实例
IoHandler :这个接口负责编写业务逻辑,也就是接收、发送数据的地方。这也是实际开发过程中需要用户自己编写的部分代码。
IoFilter :过滤器用于悬接通讯层接口与业务层接口,这个接口定义一组拦截器,这些拦截器可以包括日
志输出、黑名单过滤、数据的编码(write 方向)与解码(read 方向)等功能,其中数据的 encode与 
decode是最为重要的、也是你在使用 Mina时最主要关注的地方。

Next, let's take a look at an important class of Mina, IoHandlerAdapter, which only implements the IoHandler interface, but does not do any processing.
An IoHandler interface has the following methods (excerpted from MINA's API documentation):

void exceptionCaught(IoSession session, Throwable cause)
当接口中其他方法抛出异常未被捕获时触发此方法
void messageReceived(IoSession session, Object message)
当接收到客户端的请求信息后触发此方法
void messageSent(IoSession session, Object message)
当信息已经传送给客户端后触发此方法
void sessionClosed(IoSession session)
当连接被关闭时触发,例如客户端程序意外退出等等
void sessionCreated(IoSession session)
当一个新客户端连接后触发此方法
void sessionIdle(IoSession session, IdleStatus status)
当连接空闲时触发此方法
void sessionOpened(IoSession session)
当连接后打开时触发此方法,一般此方法与 sessionCreated 会被同时触发

Let's take a look at the Mina server network communication framework development process:

1. Import dependency: mina-core-2.0.13

img

2. Create acceptor, bind Handler, set Filter, bind port

            NioSocketAcceptor acceptor = new NioSocketAcceptor();
            acceptor.setHandler(new MyServerHandler());
            // 获取拦截器,拦截器作用:把字节转成对象
            // TextLineCodecFactory 把数据进行加解码
            acceptor.getFilterChain().addLast("codec",
                    new ProtocolCodecFilter(new TextLineCodecFactory()));
            // 5秒钟服务器和客户端没有进行读写,则进入空闲状态Idle
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 5);
            //绑定9898端口
            acceptor.bind(new InetSocketAddress(9898));

3. Create a custom Handler

package com.example.server;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class MyServerHandler extends IoHandlerAdapter {
    
    

    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
    
    
        System.out.println("exceptionCaught");
    }

    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
    
    
        String s = (String) message;
        System.out.println("messageReceived: " + s);
        session.write("server replay: " + s);
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
    
    
        System.out.println("messageSent");
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
    
    
        System.out.println("sessionClosed");
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
    
    
        System.out.println("sessionCreated");
    }

    /**
     * 会话空闲状态
     */
    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
    
    
        System.out.println("sessionIdle");
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
    
    
        System.out.println("sessionOpened");
    }

}

4. Since the default Filter: TextLineCodeFactory can only receive messages ending with a newline character, sometimes in order to meet specific needs, you need to customize a Factory

package com.example.server;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;

public class MyTextLineFactory implements ProtocolCodecFactory {
    
    

    private MyTextLineDecoder mDecoder;
    private MyTextLineEncoder mEncoder;
    private MyTextLineCumulativeDecoder mCumulativeDecoder;

    public MyTextLineFactory() {
    
    
        mDecoder = new MyTextLineDecoder();
        mEncoder = new MyTextLineEncoder();
        mCumulativeDecoder = new MyTextLineCumulativeDecoder();
    }

    // 加密
    @Override
    public ProtocolDecoder getDecoder(IoSession arg0) throws Exception {
    
    
        // return mDecoder;
        // 解决没检测到\n时的数据丢失问题
        return mCumulativeDecoder;
    }

    // 解密
    @Override
    public ProtocolEncoder getEncoder(IoSession arg0) throws Exception {
    
    
        return mEncoder;
    }

}
package com.example.server;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class MyTextLineEncoder implements ProtocolEncoder {
    
    

    @Override
    public void dispose(IoSession session) throws Exception {
    
    

    }

    @Override
    public void encode(IoSession session, Object message,
            ProtocolEncoderOutput output) throws Exception {
    
    
        String s = null;
        if (message instanceof String) {
    
    
            s = (String) message;
        }
        if (s != null) {
    
    
            // 系统默认的Encoder
            CharsetEncoder charsetEncoder = (CharsetEncoder) session
                    .getAttribute("encoder");
            if (charsetEncoder == null) {
    
    
                charsetEncoder = Charset.defaultCharset().newEncoder();
                session.setAttribute("encoder", charsetEncoder);
            }
            IoBuffer ioBuffer = IoBuffer.allocate(s.length());
            ioBuffer.setAutoExpand(true);// 自动扩展
            ioBuffer.putString(s, charsetEncoder);
            ioBuffer.flip();
            output.write(ioBuffer);
        }
    }
}
package com.example.server;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class MyTextLineDecoder implements ProtocolDecoder {
    
    

    @Override
    public void decode(IoSession session, IoBuffer ioBuffer,
            ProtocolDecoderOutput output) throws Exception {
    
    
        // 起始位置
        int startPosition = ioBuffer.position();
        // 是否还有数据
        while (ioBuffer.hasRemaining()) {
    
    
            byte b = ioBuffer.get();
            // 读取到\n
            if (b == '\n') {
    
    
                // 当前位置
                int currentPosition = ioBuffer.position();
                // 当前总长度,指向末尾
                int limit = ioBuffer.limit();
                // 截取行
                ioBuffer.position(startPosition);
                ioBuffer.limit(currentPosition);
                IoBuffer buf = ioBuffer.slice();
                // 把buf中的数据写入到dest
                byte[] dest = new byte[buf.limit()];
                buf.get(dest);
                String str = new String(dest);
                output.write(str);
                // 还原位置
                ioBuffer.position(currentPosition);
                ioBuffer.limit(limit);
            }
        }

    }

    @Override
    public void dispose(IoSession arg0) throws Exception {
    
    

    }

    @Override
    public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1)
            throws Exception {
    
    

    }
}

5. In order to solve the problem of data loss, we often use CumulativeProtocolDecoder

package com.example.server;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * 处理数据丢失
 */
public class MyTextLineCumulativeDecoder extends CumulativeProtocolDecoder {
    
    

    @Override
    protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer,
            ProtocolDecoderOutput output) throws Exception {
    
    
        // 起始位置
        int startPosition = ioBuffer.position();
        // 是否还有数据
        while (ioBuffer.hasRemaining()) {
    
    
            byte b = ioBuffer.get();
            // 读取到\n
            if (b == '\n') {
    
    
                // 当前位置
                int currentPosition = ioBuffer.position();
                // 当前总长度,指向末尾
                int limit = ioBuffer.limit();
                // 截取行
                ioBuffer.position(startPosition);
                ioBuffer.limit(currentPosition);
                IoBuffer buf = ioBuffer.slice();
                // 把buf中的数据写入到dest
                byte[] dest = new byte[buf.limit()];
                buf.get(dest);
                String str = new String(dest);
                output.write(str);
                // 还原位置
                ioBuffer.position(currentPosition);
                ioBuffer.limit(limit);
                return true;// 读取完成
            }
        }

        ioBuffer.position(startPosition);
        return false;// 读取未完成
    }
}

At this point, the entire server framework is finished. Is it simpler than Socket development? In the next section, the author will bring you a complete case, and give the corresponding jar package and source code.

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/132641219