求助!关于mina粘包的问题
完美双子 2014-07-09 10:42:35 接收的消息:HTTP头+空行+消息体
@Override
protected boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput output) throws Exception {
CharsetDecoder cd = charset.newDecoder();
int i = 1;// 行数
//int byteCount = 0;// 每行的字节数
if(in.remaining()<4){//当拆包的时候剩余长度小于4的时候的保护
return false;
}
while (in.hasRemaining()) {
// 1、分离HTTP头,获取消息体的长度
in.mark();//标志当前位置,以便reset
byte b = in.get();
buffer.put(b);
if (b == "\n".getBytes()[0] && i <= 8) {
buffer.flip();
String line = buffer.getString(buffer.limit(), cd);
httpHeader.append(line);
if (line.contains("Content-Length")) {// 第6行,contentLength
contentLength = Integer.parseInt(line.split(":")[1].trim());
session.setAttribute(CCBCodecFactory.SESSION_HTTP_LENGTH,contentLength);
}
buffer.clear();
i++;
}
if (i == 9) {
System.out.println("获取的HTTP头信息:" + httpHeader.toString());
session.setAttribute(CCBCodecFactory.SESSION_HTTP_CONTEXT,httpHeader.toString());
// 2、解密报文,in.remaining()返回position和limit之前的字节数
try {
if (in.remaining() < contentLength) {
in.reset();
return false;//接收新数据,以拼凑成完整数据
} else {
int bodyLength = (Integer) session.getAttribute(CCBCodecFactory.SESSION_HTTP_LENGTH);
byte[] encryptedMessage = new byte[bodyLength];
in.get(encryptedMessage);
//业务处理 略
output.write(contents);
}
if(in.remaining()>0){
return true;
}
} catch (SecException e) {
Logger.error("报文解密失败" + e);
}
}
}
return false;
}
解码器先获取http头,得到消息体的长度,然后获取消息体 ,但是如果消息体的长度不够,新获取的数据是否和获取的HTTP头拼接呢?然后重新执行decode方法,再次获取HTTP头呢?