mina解包和发包

解包:


protected boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception {
//System.out.println("********** AMF3Decoder *************");

while(in.remaining() > 4){//有数据时,读取4字节判断消息长度
in.mark();
int size = in.getInt();
if(size > in.remaining()){//如果消息内容不够,则重置,相当于不读取size
in.reset();
System.out.println("粘包");
return false;//接收新数据,以拼凑成完整数据
}
else
{
byte bytes[] = new byte[size];
in.get(bytes, 0, size);
IoBuffer tempIn = IoBuffer.wrap(bytes);

amf3in.setInputStream(new InflaterInputStream(new DataInputStream(tempIn.asInputStream())));
try {
Object message = amf3in.readObject();
out.write(message);
in.free();
} catch (Exception e) {
in.reset();
System.out.println("粘包 Exception size:" +size +" in.remaining():"+in.remaining());
return false;
}
}
}
if(in.remaining()==0)
return true;//处理成功,让父类进行接收下个包
else
return false;
}

发包:


public void encode(IoSession session, Object message,ProtocolEncoderOutput out) throws Exception
{
//System.out.println("********** AMF3Encoder *************");
if(message instanceof String)
{
byte[] bytes = ((String) message).getBytes("UTF-8");
IoBuffer buffer = IoBuffer.allocate(bytes.length+1);
buffer.put(bytes);
buffer.put((byte) 0x0);//要在末尾写入0,表示一个流信息的结束
buffer.flip();
out.write(buffer);
buffer.free();// 清空?
buffer.clear();
}
else
{
IoBuffer buffer;

ByteArrayOutputStream stream = new ByteArrayOutputStream();
amf3out.setOutputStream(stream);
amf3out.writeObject(message);
amf3out.flush();

byte bytes[] = stream.toByteArray();
//byte bytes[] = compress(session,stream.toByteArray());
buffer = IoBuffer.allocate(bytes.length+4,false);//创建缓存
buffer.putInt(bytes.length);//总长度
//System.out.println(bytes.length);
buffer.put(bytes);//内容
buffer.flip();
out.write(buffer);
buffer.free();// 清空?
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值