Trying to send and receive a message using protobuf in java, but received an error: the protocol message contained an invalid tag (zero)

The problem occurred on the server, calling parseDelimitedFrom ().

Client end:

C2SGainCard.Builder s = C2SGainCard.newBuilder(); C2SGainCard c2s = s.build(); GameRequest.Builder reqBuilder=GameRequest.newBuilder(); reqBuilder.setBody(c2s.toByteString()); reqBuilder.setName(C2SGainCard.class.getSimpleName()); reqBuilder.setPlayerId("3"); GameRequest request=reqBuilder.build(); DataOutputStream os = new DataOutputStream(socket.getOutputStream()); os.write(request.toByteArray()); os.flush(); os.close(); socket.close(); 

Server End:

  try{ DataInputStream is = new DataInputStream(socket.getInputStream()); GameRequest gameRequest = GameRequest.parseDelimitedFrom(is); }catch(Exception ex){ System.out.println(ex.getMessage()); } 

And here is another similar question:

Client end:

  C2SSell.Builder s = C2SSell.newBuilder(); CardOnSell.Builder cardOnSell = CardOnSell.newBuilder(); cardOnSell.setId(1); cardOnSell.setPlayerId(3); cardOnSell.setCardId(1); cardOnSell.setCurrentPrice(111); cardOnSell.setFixedPrice(555); cardOnSell.setDescription("cao"); s.setCardOnSell(cardOnSell.build()); C2SSell c2s = s.build(); 
Socket handling

was the same.

Server End:

  DataInputStream is = new DataInputStream(socket.getInputStream()); byte[] b = new byte[1024]; int len=is.read(b); String as = new String(b, 0, len); GameRequest gameRequest=GameRequest.parseFrom(as.getBytes()); 

It turns out that the end of the server will break into a parseFrom () call again. But when I comment on two lines:

 cardOnSell.setCurrentPrice(111); cardOnSell.setFixedPrice(555); 

on the End client, calling parseFrom () just worked without problems. In frist, I suspected that the .proto file had some problems, and it was proven that there were no problems ... So, how does this problem arise? Is it because I skip some data before calling parseFrom ()?

+4
source share
1 answer

I can't remember exactly what parseDelimitedFrom format parseDelimitedFrom expecting, but I suspect I just want parseFrom on your server side.

It's unclear why you are using os.write(request.toByteArray()) though, or really, why you are creating a DataOutputStream . You should use only OutputStream and InputStream , writing:

 request.writeTo(socket.getOutputStream()); 

and then:

 GameRequest gameRequest = GameRequest.parseFrom(socket.getInputStream()); 

If you need a delimited version, you need to use writeDelimitedTo .

+4
source

All Articles