如何使用协议

时间:2018-06-28 16:06:52

标签: protocol-buffers protoc protobuf.js protobufjs google-protocol-buffer

我一直在尝试使用protoc cli实用程序对字符串进行编码。 注意输出仍然包含纯文本。 我在做什么错了?

osboxes@osboxes:~/proto/bin$ cat ./teststring.proto
syntax = "proto2";
message Test2 {
  optional string b = 2;
}

echo b:\"my_testing_string\"|./protoc --encode Test2 teststring.proto>result.out

result.out包含:

^R^Qmy_testing_string

协议版本libprotoc 3.6.0和libprotoc 2.5.0

2 个答案:

答案 0 :(得分:1)

只需给出一个答案即可:

写的命令应该没问题;输出 protobuf二进制文件-它就像文本一样,因为protobuf使用utf-8编码字符串,并且您的内容由字符串控制。但是,尽管如此:该文件实际上不是 文本,如果需要检查它,通常应使用十六进制查看器或类似工具。

如果您想了解文件的内部知识,https://protogen.marcgravell.com/decode是一个很好的资源-它会按照协议规则提取输入文件或十六进制字符串,并告诉您每个字节的含义(字段标题,长度前缀) ,有效载荷等)。

我猜您的文件实际上是:

(hex)10 11 6D 79 5F等

即0x10 =“字段2,长度加前缀”,0x11 = 17(有效载荷长度,编码为varint),然后将“ my_testing_string”编码为UTF8的17个字节。

答案 1 :(得分:1)

protoc --proto_path=${protobuf_path} --encode=${protobuf_message} ${protobuf_file} < ${source_file} > ${output_file}

,在这种情况下:

protoc --proto_path=~/proto/bin --encode="Test2" ~/proto/bin/teststring.proto < ${source.txt} > ./output.bin

或:

cat b:\"my_testing_string\" | protoc --proto_path=~/proto/bin --encode="Test2" ~/proto/bin/teststring.proto > ./output.bin