2013-09-26 16 views

回答

13

首先使用

sudo apt-get install protobuf-compiler 

然後從https://code.google.com/p/goprotobuf/安裝旅途協議緩衝庫的計算機上安裝protoc。達特朗版本可以在這裏找到:https://github.com/dart-lang/dart-protoc-plugin

下一步是編寫一個.proto文件,其中包含要發送的消息的定義。例子可以在這裏找到:https://developers.google.com/protocol-buffers/docs/proto

例如:

message Car { 
    required string make = 1; 
    required int32 numdoors = 2; 
} 

然後使用protoc工具編譯一展身手文件,併爲這個原型文件飛鏢文件。

要在旅途中Car對象,記得使用類型提供:

c := new(Car) 
c.Make = proto.String("Citroën") 
c.Numdoors = proto.Int32(4) 

然後,您可以發送的對象在一個http.ResponseWriter,W如下:

binaryData, err := proto.Marshal(c) 
if err != nil { 
    // do something with error 
} 
w.Write(binaryData) 

在Dart代碼,您可以獲取如下信息:

void getProtoBuffer() { 
    HttpRequest.request("http://my.url.com", responseType: "arraybuffer").then((request) { 
     Uint8List buffer = new Uint8List.view(request.response, 0, (request.response as ByteBuffer).lengthInBytes); // this is a hack for dart2js because of a bug 
     Car c = new Car.fromBuffer(buffer); 
     print(c); 
    }); 
} 

如果一切正常,您現在應該有一個Car o在您的Dart應用程序中運行:)

+0

令人驚訝的是,讀取二進制數據作爲字符串工作。你如何處理字符編碼?例如,UTF8數據不應包含某些字節序列:http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences –

+0

對不起,你是絕對正確的!原始代碼不適用於utf-8。我會更新它......完成! – ehrt1974

+0

真棒答案...你能詳細說明爲什麼這個dart2js破解是必需的嗎?我在閱讀你的答案之前就打了它,我很好奇。 – sjr