Java中协议栈开发的最佳实践

时间:2011-09-20 10:02:26

标签: java binding protocols

Java中协议栈开发的最佳实践是什么?

在这种特定情况下,我的Java应用程序将与PC外围设备“通话”,其外围设备将以协议格式传输数据。

示例:

想象一下,我的协议有一个由一个整数,一个字符串和一个整数列表组成的消息:

class MyMessage { int filed1; String filed2; LinkedList<int> field3;}

我想要的最终产品是什么,它可以做到这一点:

// Message to fill
MyMessage msg = new MyMessage();

// InputStream with the data to bind
InputStream stream = myPeripheralBus.getInputSTream();

msg.fill(stream);

// Here, msg fields are filled with the values that were on the InputStream

1 个答案:

答案 0 :(得分:2)

Google协议缓冲区项目符合您的大部分要求。 除了field3上的LinkedList数据结构,但由于g-p-b保留了重复值的顺序,我想这对你来说已经足够了。

协议缓冲区是一种以高效且可扩展的格式编码结构化数据的方法。 Google对几乎所有内部​​RPC协议和文件格式都使用Protocol Buffers。

第1步,从http://code.google.com/apis/protocolbuffers/安装g-p-b,阅读文档。

第2步,定义你的message.proto,如下所示:

message UserDetail {

  required string id = 1;
  optional string nick = 2;
  repeated double money = 3;

}

步骤3,使用protoc编译.proto并生成UserDetail.java文件。

...
public interface UserDetailOrBuilder
        extends com.google.protobuf.MessageOrBuilder {

    // required string id = 1;
    boolean hasId();

    String getId();

    // optional string nick = 2;
    boolean hasNick();

    String getNick();

    // repeated double money = 3;
    java.util.List<java.lang.Double> getMoneyList();

}

public static final class UserDetail extends
        com.google.protobuf.GeneratedMessage
        implements UserDetailOrBuilder ...

第4步,简单调用

UserDetail.parseFrom(input);
User.UserDetail t.writeTo(output);

g-p-b有其他语言插件,请检查http://code.google.com/p/protobuf/wiki/ThirdPartyAddOns