Package cn.sunsharp.ycpn.server.xmpp.codec

Source Code of cn.sunsharp.ycpn.server.xmpp.codec.XmppDecoder

package cn.sunsharp.ycpn.server.xmpp.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.jivesoftware.openfire.nio.XMLLightweightParser;

import cn.sunsharp.ycpn.server.xmpp.net.XmppIoHandler;

/**
* 将二进制文件解码成xml文件
* @author sunsharp
* CumulativeProtocolDecoder累积性的协议解码器,也就是说只要有数据发送过来,这个类就会去
* 读取数据,然后累积到内部的IoBuffer 缓冲区,但是具体的拆包(把累积到缓冲区的数据 解码为JAVA 对象)交由子类的doDecode()方法完成
* 实际上CumulativeProtocolDecoder 就是在decode()反复的调用暴漏给子类实现的doDecode()方法。
* 执行过程:
* 1、你的doDecode()方法返回true 时,CumulativeProtocolDecoder 的decode()方法会首先判断你是否在doDecode()方法中从内部的IoBuffer 缓冲区读取了数据,
*  如果没有,则会抛出非法的状态异常,也就是你的doDecode()方法返回true 就表示你已经消费了本次数据(相当于聊天室中一个完整的消息已经读取完毕)
*  进一步说,也就是此时你必须已经消费过内部的IoBuffer 缓冲区的数据(哪怕是消费了一个字节的数据)。如果验证过通过,那么CumulativeProtocolDecoder 会检查缓冲区内是否还有数据未读取,
*  如果有就继续调用doDecode()方法,没有就停止对doDecode()方法的调用,直到有新的数据被缓冲。
* 2、当你的doDecode()方法返回false 时,CumulativeProtocolDecoder 会停止对doDecode()方法的调用,但此时如果本次数据还有未读取完的,
*  就将含有剩余数据的IoBuffer 缓冲区保存到IoSession 中,以便下一次数据到来时可以从IoSession 中提取合并。
*  如果发现本次数据全都读取完毕,则清空IoBuffer 缓冲区。
* 简而言之,当你认为读取到的数据已经够解码了,那么就返回true,否则就返回false。
*  这个CumulativeProtocolDecoder 其实最重要的工作就是帮你完成了数据的累积,因为这个工作是很烦琐的
*/
public class XmppDecoder extends CumulativeProtocolDecoder {
  @Override
  protected boolean doDecode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) throws Exception {
    //XMLLightweightParser 是一個輕量級xml解析器
    //session创建的时候,初始化的这个解析器实例:XMLLightweightParser parser = new XMLLightweightParser("UTF-8");
        XMLLightweightParser parser = (XMLLightweightParser) session
                                       .getAttribute(XmppIoHandler.XML_PARSER); // 二进制格式转换为xml
            parser.read(in);
         // 判断是否还有数据可读取
        if (parser.areThereMsgs()) {
          // 将二进制数据转解析成xml
            for (String stanza : parser.getMsgs()) {
                out.write(stanza);
            }
        }
        return !in.hasRemaining();
  }
}
TOP

Related Classes of cn.sunsharp.ycpn.server.xmpp.codec.XmppDecoder

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.