If you have a large amount of typed data in an sql database on my server, how do you send this data to a dart client using protocol buffers?
You can use protobuf inside any program, that has no need to be client/server. If you need to exchange data, and want them to be strongly typed, protobuf is a nice option (fast & reliable).
Protocol Buffers (Protobuf) is a free and open-source cross-platform data format used to serialize structured data. It is useful in developing programs to communicate with each other over a network or for storing data.
For those who are not aware of it, Gogo ProtoBuf is a fork of the original ProtoBuf APIv1 that includes a custom code generator with optional support for many performance related features.
First install protoc on your computer using
sudo apt-get install protobuf-compiler
Then install the go protocol buffer library from https://code.google.com/p/goprotobuf/. The dartlang version can be found here: https://github.com/dart-lang/dart-protoc-plugin.
The next step is to write a .proto file containing a definition of the message to be sent. examples can be found here: https://developers.google.com/protocol-buffers/docs/proto.
For example:
message Car {
required string make = 1;
required int32 numdoors = 2;
}
Then use the protoc tool to compile a go file and a dart file for this proto file.
To create a Car object in go, remember to use the types provided:
c := new(Car)
c.Make = proto.String("Citroën")
c.Numdoors = proto.Int32(4)
Then you can send the object over an http.ResponseWriter, w as follows:
binaryData, err := proto.Marshal(c)
if err != nil {
// do something with error
}
w.Write(binaryData)
In the Dart code, you can fetch the information as follows:
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);
});
}
If everything worked, you should now have a Car object in your Dart application :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With