2011-09-20 28 views
4

Java中協議棧開發的最佳實踐是什麼?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 
+0

這可能會幫助:http://stackoverflow.com/questions/7106762/how-以發送 - 例如-複雜 - 己二進制協議數據準確-使用的Java字節 – beny23

+0

可能相關:http://stackoverflow.com/questions/644737/are-there-any-java-frameworks-for二進制文件解析 – beny23

+0

問什麼是bes設備溝通的方式有點模糊,因爲沒有應用程序。實際需要傳達多少數據?需要在你的設備和PC之間來回發生多少次這種事情? – Sheena

回答

2

谷歌協議緩衝項目匹配您的大多數要求。 除了在字段3 LinkedList的數據結構,但由於G-P-B保存重複值的順序,我想這足以讓你。

協議緩衝器處於高效而可擴展的格式編碼的結構化數據的方法。谷歌幾乎所有的內部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); 

GPB有其他語言的插件,檢查http://code.google.com/p/protobuf/wiki/ThirdPartyAddOns

+0

我不喜歡這種方法,但會爲我節省很多工作。 GPB是否允許擴展?我的一個問題是有些消息不是非常線性的,所以我需要在序列化和反序列化方面有一定的靈活性。 – rnunes