求助!关于mina粘包的问题

完美双子 完美双子 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
接收的消息: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头呢?
...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
完美双子
Java 51,407 成员 86,128 内容