Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP、UDP/IP协议栈的通信框架(然,也可以提供JAVA 对象的序列化服务、虚拟机管道通信服务等),Mina 可以帮助我们快速开发高性能、高扩展性的网络通信应用,Mina 提供了事件驱动、异步(Mina 的异步IO 默认使用的是JAVA NIO 作为底层支持)操作的编程模型。Mina 主要有1.x 和2.x 两个分支,这里我们讲解最新版本2.0,如果你使用的是Mina 1.x,那么可能会有一些功能并不适用。学习本文档,需要你已掌握JAVA IO、JAVA NIO、JAVASocket、JAVA 线程及并发库(java.util.concurrent.*)的知识。Mina 同时提供了网络通信的Server 端、Client 端的封装,无论是哪端,Mina 在整个网通通信结构中都处于如下的位置:
可见Mina 的API 将真正的网络通信与我们的应用程序隔离开来,你只需要关心你要发送、接收的数据以及你的业务逻辑即可。同样的,无论是哪端,Mina 的执行流程如下所示:
(1.) IoService:这个接口在一个线程上负责套接字的建立,拥有自己的Selector,监听是否有连接被建立。
(2.) IoProcessor:这个接口在另一个线程上负责检查是否有数据在通道上读写,也就是说它也拥有自己的Selector,这是与我们使用JAVA NIO 编码时的一个不同之处,通常在JAVA NIO 编码中,我们都是使用一个Selector,也就是不区分IoService与IoProcessor 两个功能接口。另外,IoProcessor 负责调用注册在IoService 上的过滤器,并在过滤器链之后调用IoHandler。
(3.) IoFilter:这个接口定义一组拦截器,这些拦截器可以包括日志输出、黑名单过滤、数据的编码(write 方向)与解码(read 方向)等功能,其中数据的encode 与decode是最为重要的、也是你在使用Mina 时最主要关注的地方。
(4.) IoHandler:这个接口负责编写业务逻辑,也就是接收、发送数据的地方。
Mina自带的过滤器(部分)
下面我们写一个 例子 :1个mina 的客户端和服务器端,完成双方的通讯,并且服务器端是使用了 mina的 BlacklistFilter 黑名单过滤器,用来防止非法的客户端的访问
服务器端:MinaTimeServer.java
- package cn.com.xinli.mina;
- import java.io.IOException;
- import java.net.InetAddress;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import java.util.Date;
- import org.apache.mina.core.service.IoAcceptor;
- import org.apache.mina.core.service.IoHandlerAdapter;
- import org.apache.mina.core.session.IdleStatus;
- import org.apache.mina.core.session.IoSession;
- import org.apache.mina.filter.codec.ProtocolCodecFilter;
- import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
- import org.apache.mina.filter.firewall.BlacklistFilter;
- import org.apache.mina.filter.logging.LoggingFilter;
- import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
- public class MinaTimeServer {
- public static final int PORT = 9123;
- public static void main(String[] args)throws IOException {
- IoAcceptor acceptor = new NioSocketAcceptor();
- BlacklistFilter blacklistFilter=new BlacklistFilter();
- InetAddress[] address= new InetAddress[1];
- address[0]=InetAddress.getByName("169.254.11.186");
- blacklistFilter.setBlacklist(address);
- acceptor.getFilterChain().addFirst("black",blacklistFilter);
- acceptor.getFilterChain().addLast("logger", new LoggingFilter());
- acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK"))));
- acceptor.setHandler(new TimeServerHandler());
- acceptor.getSessionConfig().setReadBufferSize(2048);
- acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
- acceptor.bind(new InetSocketAddress(PORT));
- System.out.println("MINA Time Server started,bind port:"+PORT);
- }
- }
- 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();
- System.out.println("str:"+str);
- if(str.trim().equalsIgnoreCase("quit"))
- {
- session.close(true);
- return;
- }
- Date date = new Date();
- session.write(date.toString());
- System.out.println("Message written...");
- session.close(true);
- }
- @Override
- public void sessionIdle(IoSession session,IdleStatus status)throws Exception
- {
- System.out.println("IDLE " + session.getIdleCount(status));
- }
- @Override
- public void messageSent(IoSession session, Object message) throws Exception
- {
- // TODO Auto-generated method stub
- super.messageSent(session, message);
- }
- }
客户端:MinaTimeClinet.java
- package cn.com.xinli.mina;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import org.apache.mina.core.service.IoConnector;
- import org.apache.mina.core.service.IoHandlerAdapter;
- import org.apache.mina.core.session.IoSession;
- 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.filter.firewall.BlacklistFilter;
- import org.apache.mina.transport.socket.nio.NioSocketConnector;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class MinaTimeClinet
- {
- public static void main(String[] args)
- {
- IoConnector connector=new NioSocketConnector();
- connector.setConnectTimeoutMillis(30000);
- connector.getFilterChain().addLast("codec",
- new ProtocolCodecFilter(
- new TextLineCodecFactory(
- Charset.forName("GBK")
- // LineDelimiter.WINDOWS.getValue(),
- // LineDelimiter.WINDOWS.getValue()
- )
- )
- );
- connector.setHandler(new ClientHandler("你好!\r\n 大家好!"));
- connector.connect(new InetSocketAddress("localhost", 9123));
- connector.dispose();
- }
- }
- class ClientHandler extends IoHandlerAdapter
- {
- private final String values;
- public ClientHandler(String values)
- {
- this.values = values;
- }
- @Override
- public void sessionOpened(IoSession session)
- {
- session.write(values);
- //session.close(true);
- //return;
- }
- }
运行结果:
MINA Time Server started,bind port:9123
0 [NioProcessor-1] INFO org.apache.mina.filter.logging.LoggingFilter(158) - CREATED
0 [NioProcessor-1] INFO org.apache.mina.filter.logging.LoggingFilter(158) - OPENED
63 [NioProcessor-1] INFO org.apache.mina.filter.logging.LoggingFilter(140) - RECEIVED: HeapBuffer[pos=0 lim=18 cap=2048: C4 E3 BA C3 A3 A1 0D 0A 20 B4 F3 BC D2 BA C3 A3...]
str:你好!
Message written...
str: 大家好!
Message written...
94 [NioProcessor-1] INFO org.apache.mina.filter.logging.LoggingFilter(140) - SENT: HeapBuffer[pos=0 lim=29 cap=32: 53 75 6E 20 4A 61 6E 20 31 30 20 31 33 3A 33 37...]
94 [NioProcessor-1] INFO org.apache.mina.filter.logging.LoggingFilter(140) - SENT: HeapBuffer[pos=0 lim=0 cap=0: empty]
125 [NioProcessor-1] INFO org.apache.mina.filter.logging.LoggingFilter(158) - CLOSED
如果客户端使用的黑名单中的IP,则服务器端 拒绝连接:
MINA Time Server started,bind port:9123
0 [NioProcessor-1] WARN org.apache.mina.filter.firewall.BlacklistFilter(230) - Remote address in the blacklist; closing.
0 [NioProcessor-1] WARN org.apache.mina.filter.firewall.BlacklistFilter(230) - Remote address in the blacklist; closing.
0 [NioProcessor-1] WARN org.apache.mina.filter.firewall.BlacklistFilter(230) - Remote address in the blacklist; closing.