设为首页 收藏本站
查看: 920|回复: 0

[经验分享] Apache Mina的学习应用(三)

[复制链接]

尚未签到

发表于 2017-1-7 07:59:37 | 显示全部楼层 |阅读模式
  在客户端和服务端的中定义相关的业务逻辑类的实现:通过实现IoHandler 中实现方法,操作各种业务。
  一般的开发中采用IoHandlerAdapter,通过重写部分的方法实现的相关的业务逻辑;
  IoHandler
  IoHandler具有以下功能

  • sessionCreated
    sessionCreated
  • sessionOpened
    sessionOpened
  • sessionClosed
    sessionClosed
  • sessionIdle
    sessionIdle
  • exceptionCaught
    exceptionCaught
  • messageReceived
    messageReceived
  • messageSent
    messageSent
  sessionCreated事件
  
Session Created event is fired when a new connection is created.

  会话创建事件被激发时,一个新的连接被创建。
  
For TCP its the result of connection accept, and for UDP this is generated when a UDP packet is received.

  对于TCP的连接其结果接受,这是为UDP时生成一个UDP数据包接收。
  
This function can be used to initialize session attributes, and perform one time activities for a particular connection.

  该功能可用于初始化会话属性,并执行一次活动的特定连接。
  
This function is invoked from the I/O processor thread context, hence should be implemented in a way that it consumes minimal amount of time, as the same thread handles multiple sessions.

  调用此函数从I / O处理器线程上下文,因此应该采取一种方式,它消耗最少量的时间,相同的线程处理多个会话执行。
sessionOpened Event
sessionOpened事件

  
Session opened event is invoked when a connection is opened.

  调用的事件是打开一个连接。
  
Its is always called after sessionCreated event.
它总是sessionCreated事件后调用。
If a thread model is configured, this function is called in a thread other than the I/O processor thread.

  如果一个线程模型配置,该函数被调用的线程比I / O处理器线程等。
sessionClosed Event
sessionClosed事件

  
Session Closed event is closed, when a session is closed.

  
会话关闭
时,当一个会话结束。
  
Session cleaning activities like cash cleanup can be performed here.

sessionIdle Event
sessionIdle事件

  
Session Idle event is fired when a session becomes idle.

  会议空闲事件被激发时,会变为空闲。
  
This function is not invoked for UDP transport.

  此功能没有援引UDP传输。
exceptionCaught Event
exceptionCaught事件

  
This functions is called, when an Exception is thrown by user code or by MINA.

  这个函数被调用,当异常是由用户代码或MINA的异常。
  
The connection is closed, if its an IOException.
连接关闭,如果它的一个IOException。
messageReceived Event
messageReceived事件

  
Message Received event is fired whenever a message is received.

  消息收稿事件被激发时,收到一条消息。
  
This is where the most of the processing of an application happens.

  这就是对一个应用程序处理大部分发生。
  
You need to take care of all the message type you expect here.

  您需要考虑所有类型的信息在这里照顾你期望。
messageSent Event
messageSent事件

  
Message Sent event is fired, whenever a message aka response has been sent(calling IoSession.write()).
消息发送的事件被激发,每当有消息又名反应已发送(呼叫IoSession.write())。
  客户端的业务逻辑处理器:
  源代码如下:
  package cn.com.unutrip.java.opensource.mina.sumup;
  
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  import cn.com.unutrip.java.opensource.mina.sumup.message.AddMessage;
import cn.com.unutrip.java.opensource.mina.sumup.message.ResultMessage;
/**
 *
 * 处理所有I / O活动的MINA的激發。
 *  The interface is hub of all activities done at the end of the Filter Chain.
 *  该接口是在过滤器链的末端进行的所有活动的中心。
* IoHandler has following functions IoHandler具有以下功能
* sessionCreated  :
*  会话创建事件被激发时,一个新的连接被创建。 For TCP its the result of connection accept, and for UDP this is generated when a UDP packet is received.对于TCP的连接其结果接受,这是为UDP时生成一个UDP数据包接收。 This function can be used to initialize session attributes, and perform one time activities for a particular connection.该功能可用于初始化会话属性,并执行一次活动的特定连接。
*This function is invoked from the I/O processor thread context, hence should be implemented in a way that it consumes minimal amount of time, as the same thread handles multiple sessions.调用此函数从I / O处理器线程上下文,因此应该采取一种方式,它消耗最少量的时间,相同的线程处理多个会话执行。
*
* sessionOpened  :会话开始一个连接时调用此事件,它总在sessionCreated事件后调用,如果一个线程模型配置
* 该函数被调用的的线程IoHandler。

* sessionClosed  : 当一个会话结束,session清理活动的活动的连接。

* sessionIdle  : 此方法被激发时,会变成空闲,此功能没有援引UDP传输。

* exceptionCaught   : 当用户代码或者mina异常是,连接关闭,如果它的一个连接IOException
*
* messageReceived :  当接受到一个消息时被激发,对应一个应用程序的处理的大部分业务逻辑,

* messageSent  : 消息发送的时间被激发,
*
*  调用的事件是打开一个连接。 Its is always called after sessionCreated event.它总是sessionCreated事件后调用。
*   If a thread model is configured, this function is called in a thread other than the I/O processor thread.
*   如果一个线程模型配置,该函数被调用的线程比I / O处理器线程等。
  *
 * 客户端业务处理器的应用
 *
 * @author longgangbai
 *
 */
public class ClientSessionHandler extends IoHandlerAdapter {
  private final static Logger logger = LoggerFactory.getLogger(ClientSessionHandler.class);
         
          private final int[] values;
     
          private boolean finished;
     
          public ClientSessionHandler(int[] values) {
              this.values = values;
          }
     
          public boolean isFinished() {
              return finished;
          }
          /**
           * 
           *  调用的事件是打开一个连接。 Its is always called after sessionCreated event.
           *  它总是sessionCreated事件后调用。
           *  If a thread model is configured, this function is called in a thread other than the I/O processor thread.
           *  如果一个线程模型配置,该函数被调用的线程比I / O处理器线程等。
           */
          @Override
          public void sessionOpened(IoSession session) {
              logger.error("ClientSessionHandler =%%%%%%%%%%%%%%%%%%%%%%%%%%%sessionOpened ");
              // send summation requests
              for (int i = 0; i < values.length; i++) {
                  AddMessage m = new AddMessage();
                  m.setSequence(i);
                  m.setValue(values);
                  session.write(m);
              }
          }
          /**
           * 接受来自服务端的数据信息
           * 接受到消息事件被激发时,收到一条消息。
           *  This is where the most of the processing of an application happens.
           * 这就是对一个应用程序处理大部分发生。
           *  You need to take care of all the message type you expect here.
           *  您需要考虑所有类型的信息在这里照顾你期望。(重要的业务逻辑的写这里)
           */
          @Override
          public void messageReceived(IoSession session, Object message) {
              logger.error("ClientSessionHandler =%%%%%%%%%%%%%%%%%%%%%%%%%%%messageReceived ");
              // server only sends ResultMessage. otherwise, we will have to identify
              // its type using instanceof operator.
              ResultMessage rm = (ResultMessage) message;
              if (rm.isOk()) {
                  // server returned OK code.
                  // if received the result message which has the last sequence
                  // number,
                  // it is time to disconnect.
                  if (rm.getSequence() == values.length - 1) {
                      // print the sum and disconnect.
                      logger.error("The sum: " + rm.getValue());
                      session.close(true);
                      finished = true;
                  }
              } else {
                  // seever returned error code because of overflow, etc.
                  logger.error("Server error, disconnecting...");
                  session.close(true);
                  finished = true;
              }
          }
     
         /**
          * 发生异常时的操作
          * 当异常是由用户代码或MINA的异常。 The connection is closed, if its an IOException.连接关闭,如果它的一个IOException
          */
         @Override
         public void exceptionCaught(IoSession session, Throwable cause) {
            logger.error("ClientSessionHandler =%%%%%%%%%%%%%%%%%%%%%%%%%%%exceptionCaught ");
            session.close(true);
         }
}
服务端的业务逻辑处理器:
  package cn.com.unutrip.java.opensource.mina.sumup;
  import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  import cn.com.unutrip.java.opensource.mina.sumup.message.AddMessage;
import cn.com.unutrip.java.opensource.mina.sumup.message.ResultMessage;
/**
 *  创建服务端的业务处理器
 * @author longgangbai
 *
 */
public class ServerSessionHandler extends IoHandlerAdapter{
    private static final String SUM_KEY="sum";
    private final static Logger logger=LoggerFactory.getLogger(ServerSessionHandler.class);
   
    @Override
    public void sessionOpened(IoSession session){
 logger.error("ServerSessionHandler =%%%%%%%%%%%%%%%%%%%%%%%%%%%sessionOpened ");
 //设置Idle的时间为60秒
 session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
 //初始化总的和为0
 session.setAttribute(SUM_KEY,new Integer(0));
    }
    @Override
    public void sessionIdle(IoSession session,IdleStatus statis)
    {
 logger.error("ServerSessionHandler =%%%%%%%%%%%%%%%%%%%%%%%%%%%sessionIdle ");
 logger.info("Disconnecting the idle.");
 // disconnect an idle client
 session.close(true);
  }
   
     @Override
     public void exceptionCaught(IoSession session, Throwable cause) {
  logger.error("ServerSessionHandler =%%%%%%%%%%%%%%%%%%%%%%%%%%%exceptionCaught ");
         // close the connection on exceptional situation
          session.close(true);
      }
  @Override
    public void messageReceived(IoSession session ,Object message){
  logger.error("ServerSessionHandler =%%%%%%%%%%%%%%%%%%%%%%%%%%%messageReceived ");
  //客户端发送的对象必须住注册的对象一致
 AddMessage am=(AddMessage)message;
 //将客户端的发送的数据添加到当前总的金额中
 int sum=(Integer)session.getAttribute(SUM_KEY);
 int value=am.getValue();
 long expectedsum=(long)sum+value;
 
 if(expectedsum>Integer.MAX_VALUE||expectedsum<Integer.MIN_VALUE)
 {
     //
     ResultMessage rm=new ResultMessage();
     rm.setSequence(am.getSequence());
     rm.setOk(false);
     session.write(rm);
 }else{
      sum=(int)expectedsum;
      session.setAttribute(SUM_KEY,new Integer(sum));
      ResultMessage rm=new ResultMessage();
      rm.setSequence(am.getSequence());
      rm.setOk(true);
      rm.setValue(sum);
      session.write(rm);
 }
    }
  }
  文章尚未写完,请关注下文。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-324858-1-1.html 上篇帖子: apache的作用和tomcat的区别(转) 下篇帖子: Apache中的哈希表剖析(3)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表