Apache MINA 2 是一个开发高性能和高可伸缩性网络应用程序的网络应用框架。它提供了一个抽象的事件驱动的异步 API,可以使用 TCP/IP、UDP/IP、串口和虚拟机内部的管道等传输方式。Apache MINA 2 可以作为开发网络应用程序的一个良好基础。

Apache MINA是非常著名的基于java nio的通信框架,以前都是自己直接使用udp编程,新项目选型中考虑到网络通信可能会用到多种通信方式,因此使用了MINA。

本文结构:

(1)客户端和服务器代码 ;虽然是udp的,但是mina的优美的设计使得所有的通信方式能够以统一的形式使用,perfect。当然注意的是,不同的通信方式,背后的机理和有效的变量、状态是有区别的,所以要精通,那还是需要经验积累和学习的。

(2)超时 和Session的几个实际问题

(3)心跳 ,纠正几个错误

既然是使用,废话少说,直接整个可用的例子。当然了,这些代码也不是直接可用的,我们应用的逻辑有点复杂,不会这么简单使用的。

请参考mina的example包和文档http://mina.apache.org/udp-tutorial.html 。

版本2.0 RC1

1.1 服务器端

  1. NioDatagramAcceptor acceptor =  new  NioDatagramAcceptor();
  2. acceptor.setHandler(new  MyIoHandlerAdapter()); //你的业务处理,最简单的,可以extends IoHandlerAdapter
  3. DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
  4. chain.addLast("keep-alive" ,  new  HachiKeepAliveFilterInMina());  //心跳
  5. chain.addLast("toMessageTyep" ,  new  MyMessageEn_Decoder());
  6. //将传输的数据转换成你的业务数据格式。比如下面的是将数据转换成一行行的文本
  7. //acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
  8. chain.addLast("logger" ,  new  LoggingFilter());
  9. DatagramSessionConfig dcfg = acceptor.getSessionConfig();
  10. dcfg.setReuseAddress(true );
  11. acceptor.bind(new  InetSocketAddress(ClusterContext.getHeartBeatPort()));

1.2 客户端

  1. NioDatagramConnector connector =  new  NioDatagramConnector();
  2. connector.setConnectTimeoutMillis(60000L);
  3. connector.setConnectTimeoutCheckInterval(10000 );
  4. connector.setHandler(handler);
  5. DefaultIoFilterChainBuilder chain = connector.getFilterChain();
  6. chain.addLast("keep-alive" ,  new  HachiKeepAliveFilterInMina()); //心跳
  7. chain.addLast("toMessageTyep" ,  new  MyMessageEn_Decoder());
  8. chain.addLast("logger" ,  new  LoggingFilter());
  9. ConnectFuture connFuture = connector.connect(new  InetSocketAddress( "10.1.1.1" , 8001 ));
  10. connFuture.awaitUninterruptibly();
  11. IoSession session = connFuture.getSession();
  12. //发送消息长整型 1000
  13. IoBuffer buffer = IoBuffer.allocate(8 );
  14. buffer.putLong(1000 );
  15. buffer.flip();
  16. session.write(buffer);
  17. //关闭连接
  18. session.getCloseFuture().awaitUninterruptibly();
  19. connector.dispose();

2. 超时的几个经验总结:

udp session默认是60秒钟超时,此时状态为closing,数据就发不出去了。

Session的接口是IoSession,udp的最终实现是NioSession。如果交互在60秒内不能处理完成,就需要使用Keep-alive机制,即心跳机制。

3. 心跳 机制

在代码中已经使用了心跳机制,是通过mina的filter实现的,mina自身带的心跳机制好处在于,它附加了处理,让心跳消息不会传到业务层,在底层就完成了。

在上面代码实现中的HachiKeepAliveFilterInMina如下:

  1. public   class  HachiKeepAliveFilterInMina  extends  KeepAliveFilter {
  2. private   static   final   int  INTERVAL =  30 ; //in seconds
  3. private   static   final   int  TIMEOUT =  10 ;  //in seconds
  4. public  HachiKeepAliveFilterInMina(KeepAliveMessageFactory messageFactory) {
  5. super (messageFactory, IdleStatus.BOTH_IDLE,  new  ExceptionHandler(), INTERVAL, TIMEOUT);
  6. }
  7. public  HachiKeepAliveFilterInMina() {
  8. super ( new  KeepAliveMessageFactoryImpl(), IdleStatus.BOTH_IDLE,  new  ExceptionHandler(), INTERVAL, TIMEOUT);
  9. this .setForwardEvent( false );  //此消息不会继续传递,不会被业务层看见
  10. }
  11. }
  12. class  ExceptionHandler  implements  KeepAliveRequestTimeoutHandler {
  13. public   void  keepAliveRequestTimedOut(KeepAliveFilter filter, IoSession session)  throws  Exception {
  14. System.out.println("Connection lost, session will be closed" );
  15. session.close(true );
  16. }
  17. }
  18. /**
  19. * 继承于KeepAliveMessageFactory,当心跳机制启动的时候,需要该工厂类来判断和定制心跳消息
  20. * @author Liu Liu
  21. *
  22. */
  23. class  KeepAliveMessageFactoryImpl  implements  KeepAliveMessageFactory {
  24. private   static   final   byte  int_req = - 1 ;
  25. private   static   final   byte  int_rep = - 2 ;
  26. private   static   final  IoBuffer KAMSG_REQ = IoBuffer.wrap( new   byte []{int_req});
  27. private   static   final  IoBuffer KAMSG_REP = IoBuffer.wrap( new   byte []{int_rep});
  28. public  Object getRequest(IoSession session) {
  29. return  KAMSG_REQ.duplicate();
  30. }
  31. public  Object getResponse(IoSession session, Object request) {
  32. return  KAMSG_REP.duplicate();
  33. }
  34. public   boolean  isRequest(IoSession session, Object message) {
  35. if (!(message  instanceof  IoBuffer))
  36. return   false ;
  37. IoBuffer realMessage = (IoBuffer)message;
  38. if (realMessage.limit() !=  1 )
  39. return   false ;
  40. boolean  result = (realMessage.get() == int_req);
  41. realMessage.rewind();
  42. return  result;
  43. }
  44. public   boolean  isResponse(IoSession session, Object message) {
  45. if (!(message  instanceof  IoBuffer))
  46. return   false ;
  47. IoBuffer realMessage = (IoBuffer)message;
  48. if (realMessage.limit() !=  1 )
  49. return   false ;
  50. boolean  result = (realMessage.get() == int_rep);
  51. realMessage.rewind();
  52. return  result;
  53. }
  54. }

有人说:心跳机制的filter只需要服务器端具有即可——这是错误 的,拍着脑袋想一想,看看factory,你就知道了。心跳需要通信两端的实现 。

另外,版本2.0 RC1中,经过测试,当心跳的时间间隔INTERVAL设置为60s(Session的存活时间)的时候心跳会失效,所以最好需要小于60s的间隔。

最新文章

  1. Java 静态变量,常量和方法
  2. 使用USBWriter做U盘启动盘后容量变小的解决办法
  3. CODESOFT中线条形状该如何绘制
  4. [shell基础]——sed命令
  5. html+css学习笔记 2[标签]
  6. Treimu更新记录1.2.9.0
  7. 【Android】实现动态显示隐藏密码输入框的内容
  8. linux sort,uniq,cut,wc命令详解 (转)
  9. SEO要领:8文章主持技巧(两)
  10. windown 下最简单的安装mysql方式
  11. 在Python程序中的进程操作,multiprocess.Process模块
  12. luogu p1652 圆
  13. Vue - v-for 的延伸用法
  14. java常用设计模式六:适配器模式
  15. 工程化框架之feather
  16. 【Java面试题】21 Java中的异常处理机制的简单原理和应用。
  17. Python unittest第一篇:基础入门+命令行编译
  18. Python mock 的使用
  19. 基于FPGA实现的高速串行交换模块实现方法研究
  20. sql 取一张表的全部外键

热门文章

  1. Controller之间传递数据:协议传值
  2. Linux下PS1、PS2、PS3、PS4使用详解
  3. tcp/ip程序
  4. iOS 中通过使用Google API获得Google服务
  5. Java for LeetCode 067 Add Binary
  6. 在一个JSP页面中包含另一个JSP页面的三种方式
  7. HDU2084基础DP数塔
  8. 天使之城(codevs 2821)
  9. C++ friend
  10. commons-fileupload实现文件上传下载