我正在编写一个网络应用程序,它发送和接收很多不同种类的二进制数据包,并且我试图尽可能简单地向我的应用程序添加新的数据包。读取/写入二进制结构:如何简化此代码?
现在,我创建了一个Packet
类,并为每个不同类型的数据包创建它的子类。然而,它并不像看起来那么干净。我已经结束了这样的代码:
static class ItemDesc extends Packet {
public final int item_id;
public final int desc_type;
public final String filename;
public final String buf;
public ItemDesc(Type t, int item_id, int desc_type, String filename, String buf) {
super(t); // sets type for use in packet header
this.item_id = item_id;
this.desc_type = desc_type;
this.filename = filename;
this.buf = buf;
}
public ItemDesc(InputStream i) throws IOException {
super(i); // reads packet header and sets this.input
item_id = input.readInt();
desc_type = input.readByte();
filename = input.readStringWithLength();
buf = input.readStringWithLength();
}
public void writeTo(OutputStream o) throws IOException {
MyOutputStream dataOutput = new MyOutputStream();
dataOutput.writeInt(item_id);
dataOutput.writeByte(desc_type);
dataOutput.writeStringWithLength(filename);
dataOutput.writeStringWithLength(buf);
super.write(dataOutput.toByteArray(), o);
}
}
什么困扰我关于这种方法是代码重复 - 我重复数据包结构四次。我很乐意避免这种情况,但我看不到一个合理的方法来简化它。
如果我在Python写我会创造一切可能的字段类型的字典,然后像这样定义新的数据包类型:
ItemDesc = [('item_id', 'int'), ('desc_type', 'byte'), ...]
我想,我可以做任何功能性语言类似的东西。但是,我无法看到采用这种方法处理Java的方法。
(也许我只是太迂腐,或者我习惯了函数式编程和编写代码编写代码,这样我就可以避免任何重复:))
预先感谢您的任何建议。
它看起来不错。我怀疑你可以减少代码。 – ChaosPandion 2009-09-04 00:06:08