解包:
发包:
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();// 清空?
}
}