六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 57|回复: 0

转:模拟Mina2的TextLineCodecFactory中的TextLineDecoder解码器

[复制链接]

升级  11%

65

主题

65

主题

65

主题

举人

Rank: 3Rank: 3

积分
233
 楼主| 发表于 2013-2-4 13:45:24 | 显示全部楼层 |阅读模式
转自:http://hi.baidu.com/huahua035/blog/item/f41f104ff73b0b19b3de05a4.html
模拟Mina2的TextLineCodecFactory中的TextLineDecoder解码器

Mina2中已经提供了TextLine解码的方式----根据文本的换行符进行解码;

注意这里的文本换行符是和操作系统相关的,比如windows是 \r\n ,linux是 \r;

我们就模拟一个windows下换行符的解码器------即看到 \r\n 就结束接受数据,把\r\n前的数据解码为字符串!

demo:

public class VamsMessageDecoder extends CumulativeProtocolDecoder {
private static Logger logger = Logger.getLogger(VamsMessageDecoder.class);
private final Charset charset;
int str_len = 0;
IoBuffer buf = IoBuffer.allocate(0).setAutoExpand(true).position(0);
public VamsMessageDecoder(Charset charset) {
   super();
   this.charset = charset;
}
@Override
protected boolean doDecode(IoSession session, IoBuffer in,
    ProtocolDecoderOutput out) throws Exception {
   String message = "";
   boolean mark1 = false;
   boolean mark2 = false;
   char temp_char;
   CharsetDecoder charsetDecoder = charset.newDecoder();
   while (in.hasRemaining()) {
    byte b = in.get();
    temp_char = (char) b;
    logger.info("---" + temp_char + "-----");
    buf.put(b);
    str_len++;
    logger.info("len-----"+str_len);
    if (b == '\r') {
     logger.info("换行01");
     mark1 = true;
     continue;
    }
    if (b == '\n' && mark1) {
     logger.info("换行02");
     mark2=true;
     break;
    }
   }
   if(mark1 && mark2){
    buf.flip();
    message = buf.getString(str_len, charsetDecoder);
    logger.info("-----------len-"+str_len+"-----str-"+ message+"----");
    str_len = 0;
    //buf = IoBuffer.allocate(0).setAutoExpand(true).position(0); // buf已经取光了,所以不用重复的初始化
    out.write(message.substring(0, message.length() - 2));
    return true;
   }
   return false;
}
}

//=============================注意=====================

注意:这里的换行符:\r\n是2个字节, \r的ASCII是13,\n的ASCII是10,千万不要把\r\n当作是字符串(“\r\n”文本换行符,而不是长度为4的字符串,注意跟 \\r\\n区分一下)
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

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