mina学习 粘包,断包处理
2013-08-02 14:06
211 查看
1.可以在过滤器中添加协议添加协议
在CodecFactory中处理
acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(new CodecFactory()));
在CodecFactory中处理
import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolEncoder; public class CodecFactory implements ProtocolCodecFactory { private ProtocolEncoder encoder; private ProtocolDecoder decoder; public CodecFactory() { this.encoder = new ResponseEncoder(); this.decoder = new RequestDecoder(); } public ProtocolEncoder getEncoder(IoSession ioSession) throws Exception { return this.encoder; } public ProtocolDecoder getDecoder(IoSession ioSession) throws Exception { return this.decoder; } }
package com.epdc.socket.server.protocol; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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; public class RequestDecoder extends CumulativeProtocolDecoder { private final static Log LOG = LogFactory.getLog(RequestDecoder.class); protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (in.remaining() > 0) {// 有数据时,读取2字节判断消息长度 byte[] sizeBytes = new byte[2]; in.mark();// 标记当前位置,以便reset in.get(sizeBytes);// 读取前2字节 int size = Integer.valueOf(HexUtil.bytes2hex(sizeBytes), 16); // 如果消息内容的长度不够则直接返回true if (size > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size in.reset(); LOG.debug("消息内容不够 断包了"); return false;// 接收新数据,以拼凑成完整数据 } else { byte[] bytes = new byte[size]; in.get(bytes, 0, size); RequestModel model= new RequestModel(sizeBytes, bytes); out.write(model); if (in.remaining() > 0) {// 如果读取内容后还粘了包,就让父类再一次进行下一次解析 LOG.debug("读取内容粘包了"); return true; } } } return false; } }
相关文章推荐
- NIO框架之MINA源码解析(四):粘包与断包处理及编码与解码
- NIO框架之MINA源码解析(四):粘包与断包处理及编码与解码
- NIO框架之MINA源码解析(四):粘包与断包处理及编码与解码
- NIO框架之MINA源码解析(四):粘包与断包处理及编码与解码
- Socket通信自定义mina 框架过滤器解析(处理粘包、断包问题)
- 通信(Netty、Mina2)【通信粘包的处理】、【数据协议】、【网络系统的安全性】
- mina处理断包和粘包
- 通信(Netty、Mina2)【通信粘包的处理】、【数据协议】、【网络系统的安全性】
- MINA框架中的编码解码以及对粘包断包的处理
- 深入解析Apache Mina源码(4)——Mina编解码以及对粘包和断包的处理
- mina自定义编解码器接收处理byte数组(同时解决数据传输中的粘包、缺包问题)
- mina处理断包和粘包
- netty学习之二 分包、组包、粘包处理
- 即时通讯下数据粘包、断包处理实例(基于CocoaAsyncSocket)
- Mina框架使用---Android客户端的实现,断线重连,粘包处理(服务端非mina)
- 即时通讯下数据粘包、断包处理实例(基于CocoaAsyncSocket)
- 即时通讯下数据粘包、断包处理实例(基于CocoaAsyncSocket)
- Python 学习笔记 - socket(粘包及其处理方式)
- Mina传输大数组,多路解码,粘包问题的处理
- mina IoBuffer 处理断包、粘包