【发布时间】:2012-10-15 12:39:34
【问题描述】:
我的应用程序通过 protobuf 从服务器向客户端发送数据。 当我在客户端反序列化发送的有效负载时,eclipse 会引发以下类型的预期:
Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
当我调用“parseFrom()”时会发生预期。我知道在大多数情况下,错误在于语法错误的 protobuf 文件。因此,我希望在这里发布 protobuf 定义就足够了:
package protobuf;
option java_package = "com.carproject.abs.demo.protobuf";
option java_outer_classname = "DesktopDevice_getCarsResponse";
message CARS {
required int64 carid = 1;
required string carname = 2;
message Carinformation {
required string street = 1;
required string postalcode = 2;
required string city = 3;
required string country = 4;
required string cartimezoneid = 5;
}
message Right {
optional string name = 1;
optional int32 type = 2;
optional int32 service = 3;
}
message PropertyType {
optional string name = 1;
optional string value = 2;
}
repeated Carinformation carinformation = 3;
repeated Right carrights = 4;
repeated PropertyType carproperties = 5;
repeated string inoid = 6;
}
这是显示数据如何在服务器端写入的代码:
// carObj returns the necessary Strings
CAR carObj = car.getCAR();
Builder newBuilder = DesktopDevice_getCarResponse.CAR.newBuilder();
newBuilder.setCarid( carObj.getCARID() );
newBuilder.setCarname( carObj.getCARNAME());
// hardcoded values here
newBuilder.getCarinformationBuilder(1).setStreet( carObj.getCARNFORMATION().getSTREET() );
newBuilder.getCarinformationBuilder(1).setPostalcode( carObj.getCARINFORMATION().getPOSTALCODE() );
newBuilder.getCarinformationBuilder(1).setCity( carObj.getCARINFORMATION().getCITY() );
newBuilder.getCarinformationBuilder(1).setCountry( fleetObj.getCARINFORMATION().getCOUNTRY() );
newBuilder.getCarinformationBuilder(1).setCartimezoneid( fleetObj.getCARINFORMATION().getCARTIMEZONEID() );
byte[] responsePayload = newBuilder.build().toByteArray();
RestServerResponseMessage responseMsg = new RestServerResponseMessage( requestMsg.getRequestId(), responsePayload, "XML");
return responseMsg;
如您所见,Server 使用 protobuf 提供的 Builder 模式来设置必要的字符串。然后将数据序列化为 byte[] 并通过 protobuf 发送回客户端。
这是我尝试解析数据的客户端代码。
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
CAR car = DesktopDevice_getCarsResponse.CARS.parseFrom(instream);
}
调用 .parseFrom 时抛出异常。服务器代码和 carObj 工作正常。我已经在我的程序中成功发送了 protobuf 数据。
【问题讨论】:
-
这和 REST 有什么关系?
-
我也在我的应用程序中使用 REST,但这与我的问题无关。删除标签
-
您是如何编写这些数据的,究竟?是否使用相同的工具和相同的 .proto 定义?另外:你是怎么写的?例如,一个常见的错误是在内存中缓冲,然后使用缓冲区的过大部分(而不仅仅是其中包含真正 protobuf 数据的缓冲区部分)。我认为我们需要查看处理读写的代码,而不是查看 .proto...
-
编辑了我的初始帖子,其中包含有关如何在服务器和客户端写入数据的编码。服务器和客户端之间的通信通过序列化作为 byte[] 工作(使用另一个 protobuf 文件成功测试)并且 carObj 为 protobuf-builder 提供有效的字符串
标签: buffer protocols protocol-buffers