Mina的ObjectSerialization、TextLine分包分析

Tcp传输数据分包不外乎3个方法:
[list]
[*]定长数据包。
[*]带数据长度的包头。
[*]在数据包之间用换行之类的特殊符号分隔。
[/list]

如果使用ObjectSerializationCodecFactory的ProtocolCodecFilter直接传输Java类对象的话,实际上会在要传输的数据前加上4个字节的来表示数据长度。关键代码如下:


public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
if (!(message instanceof Serializable)) {
throw new NotSerializableException();
}

IoBuffer buf = IoBuffer.allocate(64);
buf.setAutoExpand(true);
buf.putObject(message);//存入IoBuffer中

int objectSize = buf.position() - 4;
if (objectSize > maxObjectSize) {
throw new IllegalArgumentException(
"The encoded object is too big: " + objectSize + " (> "
+ maxObjectSize + ')');
}

buf.flip();
out.write(buf);
}

public IoBuffer putObject(Object o) {
int oldPos = position();
skip(4); // 跳过前4字节
try {
ObjectOutputStream out = new ObjectOutputStream(asOutputStream()) {
@Override
protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException {
try {
Class<?> clz = Class.forName(desc.getName());
if (!Serializable.class.isAssignableFrom(clz)) { // NON-Serializable class
write(0);
super.writeClassDescriptor(desc);
} else { // Serializable class
write(1);
writeUTF(desc.getName());
}
}
catch (ClassNotFoundException ex) { // Primitive types
write(0);
super.writeClassDescriptor(desc);
}
}
};
out.writeObject(o);
out.flush();
} catch (IOException e) {
throw new BufferDataException(e);
}

// 填充数据长度
int newPos = position();
position(oldPos);
putInt(newPos - oldPos - 4);
position(newPos);
return this;
}


而使用TextLineDecoder、TextLineEncoder则会在数据末尾添加换行符来分包。

[color=white]作者:翁志艺[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值