在androidpn中主要采用Mina进行网络通讯,其中Mina中IoHandler用来处理主要的业务逻辑。

Mina 中源代码如下:

Java代码  
  1. package org.apache.mina.core.service;
  2. import java.io.IOException;
  3. import org.apache.mina.core.session.IdleStatus;
  4. import org.apache.mina.core.session.IoSession;
  5. /**
  6. * Handles all I/O events fired by MINA.
  7. *
  8. * @author <a href="http://mina.apache.org">Apache MINA Project</a>
  9. *
  10. * @see IoHandlerAdapter
  11. */
  12. public interface IoHandler {
  13. /**
  14. * Invoked from an I/O processor thread when a new connection has been created.
  15. * Because this method is supposed to be called from the same thread that
  16. * handles I/O of multiple sessions, please implement this method to perform
  17. * tasks that consumes minimal amount of time such as socket parameter
  18. * and user-defined session attribute initialization.
  19. */
  20. void sessionCreated(IoSession session) throws Exception;
  21. /**
  22. * Invoked when a connection has been opened.  This method is invoked after
  23. * {@link #sessionCreated(IoSession)}.  The biggest difference from
  24. * {@link #sessionCreated(IoSession)} is that it's invoked from other thread
  25. * than an I/O processor thread once thread model is configured properly.
  26. */
  27. void sessionOpened(IoSession session) throws Exception;
  28. /**
  29. * Invoked when a connection is closed.
  30. */
  31. void sessionClosed(IoSession session) throws Exception;
  32. /**
  33. * Invoked with the related {@link IdleStatus} when a connection becomes idle.
  34. * This method is not invoked if the transport type is UDP; it's a known bug,
  35. * and will be fixed in 2.0.
  36. */
  37. void sessionIdle(IoSession session, IdleStatus status) throws Exception;
  38. /**
  39. * Invoked when any exception is thrown by user {@link IoHandler}
  40. * implementation or by MINA.  If <code>cause</code> is an instance of
  41. * {@link IOException}, MINA will close the connection automatically.
  42. */
  43. void exceptionCaught(IoSession session, Throwable cause) throws Exception;
  44. /**
  45. * Invoked when a message is received.
  46. */
  47. void messageReceived(IoSession session, Object message) throws Exception;
  48. /**
  49. * Invoked when a message written by {@link IoSession#write(Object)} is
  50. * sent out.
  51. */
  52. void messageSent(IoSession session, Object message) throws Exception;
  53. }

Mina中IoHandler可供处理的事件回调

sessionCreate(IoSession)

IoSession对象被创建时的回调,一般用于进行会话初始化操作。注意:与sessionOpened(IoSession)不同,IoSession对象的创建并不意味着对应底层TCP连接的建立,而仅仅代表字面意思:一个IoSession对象被创建出来了。

sessionOpened(IoSession)

IoSession对象被打开时回调。在TCP中,该事件是在TCP连接建立时触发,一般可用于发起连接建立的握手、认证等操作。

sessionIdle(IoSession,IdleStatus)

IoSession对象超时时回调。当一个IoSession对象在指定的超时时常内没有读写事件发生,就会触发该事件,一般可用于通知服务器断开长时间闲置的连接等处理。具体的超时设置可由 IoService.setWriteIdleTime(int) ,IoService.setReadIdleTime(int) ,IoService.setBothIdleTime(int)设置。

messageReceived(IoSession,Object)

当接收到IoSession对Client发送的数据时回调。

messageSent(IoSession,Object)

当发送给IoSession对Client的数据发送成功时回调。

exceptionCaught(IoSession,Throwable)

当会话过程中出现异常时回调,通常用于错误处理。

session.write(Object)方法是一个异步方法,对该方法的调用并不会阻塞,而是向Mina投递一个异步的写操作,并返回一个可用于对已投递异步写操作进行控制的WriteFuture对象。例如:调用WriteFuture的await()或awaitUninterruptibly(),可由同步等待该异步操作的完成。

在I/O处理器中实现业务逻辑的时候,对于简单的情况,一般只需要在messageReceived中对传入的消息进行处理。如果需要写回数据到对等体,用IoSession.write()即可。

另外的情况,client和server的通信协议比较复杂,client是有状态变迁的,这时可用Mina提供的状态机实现,可使用IO处理器的实现更加简单。

androidpn中XmppIoHandler源代码:

Java代码  
  1. package org.androidpn.server.xmpp.net;
  2. import java.util.Map;
  3. import java.util.concurrent.ConcurrentHashMap;
  4. import org.androidpn.server.xmpp.XmppServer;
  5. import org.apache.commons.logging.Log;
  6. import org.apache.commons.logging.LogFactory;
  7. import org.apache.mina.core.service.IoHandler;
  8. import org.apache.mina.core.session.IdleStatus;
  9. import org.apache.mina.core.session.IoSession;
  10. import org.dom4j.io.XMPPPacketReader;
  11. import org.jivesoftware.openfire.net.MXParser;
  12. import org.jivesoftware.openfire.nio.XMLLightweightParser;
  13. import org.xmlpull.v1.XmlPullParserException;
  14. import org.xmlpull.v1.XmlPullParserFactory;
  15. /**
  16. * This class is to create new sessions, destroy sessions and deliver
  17. * received XML stanzas to the StanzaHandler.
  18. *
  19. * @author Sehwan Noh (devnoh@gmail.com)
  20. */
  21. public class XmppIoHandler implements IoHandler {
  22. private static final Log log = LogFactory.getLog(XmppIoHandler.class);
  23. public static final String XML_PARSER = "XML_PARSER";
  24. private static final String CONNECTION = "CONNECTION";
  25. private static final String STANZA_HANDLER = "STANZA_HANDLER";
  26. private String serverName;
  27. private static Map<Integer, XMPPPacketReader> parsers = new ConcurrentHashMap<Integer, XMPPPacketReader>();
  28. private static XmlPullParserFactory factory = null;
  29. static {
  30. try {
  31. factory = XmlPullParserFactory.newInstance(
  32. MXParser.class.getName(), null);
  33. factory.setNamespaceAware(true);
  34. } catch (XmlPullParserException e) {
  35. log.error("Error creating a parser factory", e);
  36. }
  37. }
  38. /**
  39. * Constructor. Set the server name from server instance.
  40. */
  41. protected XmppIoHandler() {
  42. serverName = XmppServer.getInstance().getServerName();
  43. }
  44. /**
  45. * Invoked from an I/O processor thread when a new connection has been created.
  46. */
  47. public void sessionCreated(IoSession session) throws Exception {
  48. log.debug("sessionCreated()...");
  49. }
  50. /**
  51. * Invoked when a connection has been opened.
  52. */
  53. public void sessionOpened(IoSession session) throws Exception {
  54. log.debug("sessionOpened()...");
  55. log.debug("remoteAddress=" + session.getRemoteAddress());
  56. // Create a new XML parser
  57. XMLLightweightParser parser = new XMLLightweightParser("UTF-8");
  58. session.setAttribute(XML_PARSER, parser);
  59. // Create a new connection
  60. Connection connection = new Connection(session);
  61. session.setAttribute(CONNECTION, connection);
  62. session.setAttribute(STANZA_HANDLER, new StanzaHandler(serverName,
  63. connection));
  64. }
  65. /**
  66. * Invoked when a connection is closed.
  67. */
  68. public void sessionClosed(IoSession session) throws Exception {
  69. log.debug("sessionClosed()...");
  70. Connection connection = (Connection) session.getAttribute(CONNECTION);
  71. connection.close();
  72. }
  73. /**
  74. * Invoked with the related IdleStatus when a connection becomes idle.
  75. */
  76. public void sessionIdle(IoSession session, IdleStatus status)
  77. throws Exception {
  78. log.debug("sessionIdle()...");
  79. Connection connection = (Connection) session.getAttribute(CONNECTION);
  80. if (log.isDebugEnabled()) {
  81. log.debug("Closing connection that has been idle: " + connection);
  82. }
  83. connection.close();
  84. }
  85. /**
  86. * Invoked when any exception is thrown.
  87. */
  88. public void exceptionCaught(IoSession session, Throwable cause)
  89. throws Exception {
  90. log.debug("exceptionCaught()...");
  91. log.error(cause);
  92. }
  93. /**
  94. * Invoked when a message is received.
  95. */
  96. public void messageReceived(IoSession session, Object message)
  97. throws Exception {
  98. log.debug("messageReceived()...");
  99. log.debug("RCVD: " + message);
  100. // Get the stanza handler
  101. StanzaHandler handler = (StanzaHandler) session
  102. .getAttribute(STANZA_HANDLER);
  103. // Get the XMPP packet parser
  104. int hashCode = Thread.currentThread().hashCode();
  105. XMPPPacketReader parser = parsers.get(hashCode);
  106. if (parser == null) {
  107. parser = new XMPPPacketReader();
  108. parser.setXPPFactory(factory);
  109. parsers.put(hashCode, parser);
  110. }
  111. // The stanza handler processes the message
  112. try {
  113. handler.process((String) message, parser);
  114. } catch (Exception e) {
  115. log.error(
  116. "Closing connection due to error while processing message: "
  117. + message, e);
  118. Connection connection = (Connection) session
  119. .getAttribute(CONNECTION);
  120. connection.close();
  121. }
  122. }
  123. /**
  124. * Invoked when a message written by IoSession.write(Object) is sent out.
  125. */
  126. public void messageSent(IoSession session, Object message) throws Exception {
  127. log.debug("messageSent()...");
  128. }
  129. }

XmppIoHandler在加载的时候创建相关的xml解析工厂。

sessionOpened:在连接打开时候创建相关的xml的解析器和Handler处理器。

sessionClosed:关闭相关的连接。

sessionIdle:关闭相关的连接。

messageReceived:获取相关的xml解析器和handler处理器处理相关的消息。

<!-- Baidu Button BEGIN -->

androidpn的学习研究(八)androidpn 中业务类XmppIoHandler实现分析相关推荐

  1. BT源代码学习心得(八):跟踪服务器(Tracker)的代码分析(用户请求的实际处理) - 转贴自 wolfenstein (NeverSayNever)

    BT源代码学习心得(八):跟踪服务器(Tracker)的代码分析(用户请求的实际处理) author: wolfenstein 通过上一次的分析,我们已经知道了Tracker采用http协议和客户端通 ...

  2. C++语言学习(十四)——C++类成员函数调用分析

    C++语言学习(十四)--C++类成员函数调用分析 一.C++成员函数 1.C++成员函数的编译 C++中的函数在编译时会根据命名空间.类.参数签名等信息进行重新命名,形成新的函数名.函数重命名的过程 ...

  3. androidpn的学习研究(二)androidpn-server服务端启动过程的理解分析

    在Androidpn的底层主要采用的mina和openfire两大框架,其中mina主要为底层数据传输的Socket框架.下面简单说明mina的框架. Apache Mina Server 是一个网络 ...

  4. androidpn的学习研究(七)Androidpn-server的添加其他xmpp相关的协议(如查看好友列表等)...

    曾经有一个同学,在网上问我,如果想androidpn添加额外的xmpp协议的方法在怎么加呢?我当时很迷惑,后来经过一翻仔细研究androidpn发现,其实每一种处理xmpp协议方法,必须有一个Hand ...

  5. androidpn的学习研究(五)androidpn-client 常见BUG解决方法

    原文地址:http://phonepush.sinaapp.com/forum.php?mod=viewthread&tid=6&extra=page%3D1 最近有需要做手机推送方面 ...

  6. androidpn的学习研究(六)Androidpn-server的Mina编码和解码解析过程

    在许多网络应用中可能针对传输的数据进行加密操作,接收到数据之后进行解码操作. 在mina中提供许多加密和解密的解析方式: 1.带一定前缀的字符串的解析方式. 2.序列化对象的字符串解析方式. 3.分隔 ...

  7. TS学习(八) :TS中的类

    TS中类的书写 以前在js中书写类是这样的,然后我们在加上TS的类型检查你会发现报错了 class User {constructor(name:string,age:number) {this.na ...

  8. python学习随笔:python中的类

    python中的类 # 以Student 为类的名称(类名)有一个或多个单词组成,每个单词的首字母大写,其余小写 class Student:native_pace = '成都' # 直接写在类里的变 ...

  9. androidpn的学习研究(四)androidpn-client客户端几个类说明

    在androidpn的客户端几个重要的类: ServiceManager:管理消息服务和加载相关的配置. ConnectivityReceiver:处理网络状态的广播. NotificationRec ...

最新文章

  1. java jdk 1.8 配置_Java开发环境jdk 1.8安装配置方法(Win7 64位系统/windows server 2008)...
  2. android Adapter剖析理解
  3. Centos 6.4 搭建LANMP一键安装版
  4. sql 精读(一)标准 SQL 中的分析函数概念
  5. html5 js选择器,使用HTML5的JS选择器操作页面中的元素
  6. 桌面在计算机领域常用来指,桌面在计算机领域常用来指什么
  7. Java 8新特性探究(二)深入解析默认方法
  8. python重命名窗口_为《Python实现批量重命名》程序加一个GUI
  9. 20条.net编码习惯 【转】
  10. PTA: 6-5 删除单链表偶数节点 (20 分)
  11. html怎么添加视频旋转,拍摄的视频如何旋转 三种方法教你旋转视频
  12. 2020 JUSTCTF F@k3 0ff1c@l REVERSE WP
  13. VMware 苹果虚拟机 Xcode真机调试失败 设备不信任该机器
  14. JS实现:纵向表格,且可在当前行下方添加一行
  15. 学生学籍管理系统数据流图
  16. 制作 .Img 镜像文件
  17. 相机照片大小设置_我应该为运动照片使用哪些相机设置?
  18. zabbix随堂笔记
  19. Magisk模块开发指南
  20. dnf剑魂buff等级上限_DNF5.8新版buff换装提升整理以及装备选择,防止弯路

热门文章

  1. input type属性为file时(type=file),上传一次然后做更新input的change事件
  2. 任意目录下启动tomcat
  3. JQuery使用deferreds串行多个ajax请求
  4. Shell脚本批量清除Nginx缓存
  5. ORACLE取周、月、季、年的開始时间和结束时间
  6. IDEA 常用配置以及快捷
  7. jQuery 第三章
  8. 数据结构与算法-学习笔记(18)
  9. drbd相关知识点解析
  10. 使用cronolog 分割Tomcat日志 Apache日志