MINA框架的特点有:基于java NIO类库开发;采用非阻塞方式的异步传输;事件驱动;支持批量数据传输;支持TCP、UDP协议;控制反转的设计模式(支持Spring);采用优雅的松耦合架构;可灵活的加载过滤器机制;单元测试更容易实现;可自定义线程的数量,以提高运行于多处理器上的性能;采用回调的方式完成调用,线程的使用更容易。
2.MINA框架的常用类
类NioSocketAcceptor用于创建服务端监听;
类NioSocketConnector用于创建客户端连接;
类IoSession用来保存会话属性和发送消息;
类IoHandlerAdapter用于定义业务逻辑
以下为一简单例程
服务端
MinaTimeServer.java
package com.example.ninademoserver;
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.ProtocolCodecFactory;
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( (ProtocolCodecFactory) new TextLineCodecFactory( Charset.forName( "UTF-8" ))));//指定编码过滤器
acceptor.setHandler( new TimeServerHandler() );//指定业务逻辑处理器
acceptor.setDefaultLocalAddress( new InetSocketAddress(PORT) );//设置端口号
acceptor.bind();//启动监听
}
}
TimeServerHandler.java
package com.example.ninademoserver;
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;
public class TimeServerHandler extends IoHandlerAdapter {
@Override
public void sessionCreated(IoSession session) {
//会话创建时被触发
// 显示客户端的ip和端口
System.out.println(session.getRemoteAddress().toString());
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
//接收到消息后被触发
String str = message.toString();
if (str.trim().equalsIgnoreCase("quit")) {
session.close();// 结束会话
return;
}
System.out.println("Client Message is " + str);
Date date = new Date();
session.write(date.toString());// 返回当前时间的字符串
System.out.println("Message written...");
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
//发送消息后被触发
super.messageSent(session, message);
}
@Override
public void sessionClosed(IoSession session) throws Exception {
// 会话结束后被触发
super.sessionClosed(session);
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
// 会话空闲时被触发
super.sessionIdle(session, status);
}
@Override
public void sessionOpened(IoSession session) throws Exception {
// 会话开始时被触发
super.sessionOpened(session);
}
}
客户端
MinaTimeClient.java
package com.example.nimademoclient;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
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.NioSocketConnector;
public class MinaTimeClient {
public static void main(String[] args) {
// 创建客户端连接器.
NioSocketConnector connector = new NioSocketConnector();
connector.getFilterChain().addLast( "logger", new LoggingFilter() );
connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( (ProtocolCodecFactory) new TextLineCodecFactory( Charset.forName( "UTF-8" )))); //设置编码过滤器
connector.setConnectTimeout(30);
connector.setHandler(new TimeClientHandler());//设置事件处理器
ConnectFuture cf = connector.connect(
new InetSocketAddress("127.0.0.1", 9123));//建立连接
cf.awaitUninterruptibly();//等待连接创建完成
while(true){
int count = 0;
byte[] b = new byte[1024];
String s = null;
try {
count = System.in.read(b);
System.out.println(count);
s = new String(b, 0, count - 2);
} catch (IOException e) {
e.printStackTrace();
}
if(s.equals("q")){
System.out.println("break");
break;
}else{
cf.getSession().write(s);
}
}
cf.getSession().write("客户端退出");//发送消息
cf.getSession().write("quit");//发送消息
cf.getSession().getCloseFuture().awaitUninterruptibly();//等待连接断开
connector.dispose();
}
}
TimeClientHandler.java
package com.example.nimademoclient;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
public class TimeClientHandler extends IoHandlerAdapter {
public TimeClientHandler() {
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
System.out.println(message);//显示接收到的消息
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
super.messageSent(session, message);
System.out.println("sent message " + message.toString());
}
@Override
public void sessionCreated(IoSession session) throws Exception {
super.sessionCreated(session);
System.out.println("已连接至服务端" + session.getRemoteAddress());
}
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
System.out.println("会话结束");
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
super.sessionIdle(session, status);
System.out.println("空闲等待");
}
@Override
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
System.out.println("会话开始");
}
}