如果我服务器上的 sql 数据库中有大量类型化数据,如何使用 Protocol Buffer 将这些数据发送到 dart 客户端?
最佳答案
首先使用
在您的计算机上安装 protocsudo apt-get install protobuf-compiler
然后从https://code.google.com/p/goprotobuf/安装go protocol buffer库. dartlang 版本可以在这里找到: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工具为这个proto文件编译一个go文件和一个dart文件。
要在 go 中创建 Car 对象,请记住使用提供的类型:
c := new(Car)
c.Make = proto.String("Citroën")
c.Numdoors = proto.Int32(4)
然后您可以通过 http.ResponseWriter 发送对象,如下所示:
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);
});
}
如果一切正常,您现在应该在 Dart 应用程序中有一个 Car 对象 :)
关于ajax - 如何使用 Protocol Buffer 序列化 Go 结构并在 Dart over Ajax 中使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19036213/