Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dart-protobuf

I'm considering using dart-protobuf instead of JSON in one of my projects. The problem is that the library does not provide any example of how to use it, and the tests don't really help either.

I'm also a bit confused on how the parsing of .proto files would work.

So I'm looking for a simple example of how to use this library in dart.

like image 333
enyo Avatar asked Feb 14 '14 03:02

enyo


People also ask

How is Protobuf used?

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.


1 Answers

I use it and it's awesome. Below the part that was the hardest for me (de/serialization). Maybe docs are better now.

send request (query is the protocol buffer object to send)

request.send(query.writeToBuffer()); 

receive response (pb.MovieMessage is the protocol buffer object to deserialize the response to)

request.onLoad.listen((ProgressEvent e) {
  if ((request.status >= 200 && request.status < 300) ||
      request.status == 0 || request.status == 304) {

    List<int> buffer = new Uint8List.view(request.response);
    var response = new pb.MovieMessage.fromBuffer(buffer);

EDIT

My method to send a PB request to the server

Future<pb.MovieMessage> send(pb.MovieMessage query) {

  var completer = new Completer<pb.MovieMessage>();
  var uri = Uri.parse("http://localhost:8080/public/data/");

  var request = new HttpRequest()
  ..open("POST", uri.toString(), async: true)
    ..overrideMimeType("application/x-google-protobuf")
    ..setRequestHeader("Accept", "application/x-google-protobuf")
    ..setRequestHeader("Content-Type", "application/x-google-protobuf")
    ..responseType = "arraybuffer"
    ..withCredentials = true // seems to be necessary so that cookies are sent
    ..onError.listen((e) {
      completer.completeError(e);
    })
    ..onProgress.listen((e){},
        onError:(e) => _logger.severe("Error: " + e.errorMessage));

    request.onReadyStateChange.listen((e){},
        onError: (e) => _logger.severe("OnReadyStateChange.OnError: " + e.toString())
        );

    request.onLoad.listen((ProgressEvent e) {
      if ((request.status >= 200 && request.status < 300) ||
          request.status == 0 || request.status == 304) {

        List<int> buffer = new Uint8List.view(request.response);
        var response = new pb.MovieMessage.fromBuffer(buffer);
        response.errors.forEach((pb.Error e) => _logger.severe("Error: " + e.errorMessage));

        completer.complete(response);
      } else {
        completer.completeError(e);
      }
    });

    request.send(query.writeToBuffer()); 
    return completer.future;
  }
like image 128
Günter Zöchbauer Avatar answered Sep 22 '22 12:09

Günter Zöchbauer