2

I'm trying to replace my string based protocol with one that uses protobuf. I serialize move command with:

Schema<MoveCommand> schema = RuntimeSchema.getSchema(MoveCommand.class);
ProtostuffIOUtil.toByteArray(this, schema, buffer)

And my hit command with:

Schema<Hitcommand> schema = RuntimeSchema.getSchema(Hitcommand.class);
ProtostuffIOUtil.toByteArray(this, schema, buffer)

This works without problems. When i serialize the result is a byte[], this data is send over and socket to a serversocket.

On the serverside i read out the byte[] array, but how can i determine the type of the object that is inside the byte[] array? (is it and HitCommand or a MoveCommand?)

I ask this because to deserialize i need a Schema and i can only create/get the schema when i know the class of the object that is inside the byte[] array.

With my old string protocol i just had the type of the message at the beginning of the string.

I suspect i'm missing something crucial.

Tinus Tate
  • 2,237
  • 2
  • 12
  • 33

1 Answers1

2

The type of the message is not part of the serialized data. If you have no other way of specifying it, then you could create another message (maybe called Envelope) that holds either a Hitcommand or a MoveCommand. You could then always deserialize the envelope and see if Hitcommand or MoveCommand is defined.

Carsten Hoffmann
  • 901
  • 5
  • 14
  • the Envelope idea is a good one, i will try to implement it. Thanks for the idea! – Tinus Tate Oct 23 '15 at 14:52
  • (can't edit my original comment) But doesn't this mean you have to deserialize twice? First the Envelop and next the Move/Hit command. – Tinus Tate Oct 23 '15 at 14:59
  • No, your Envelope schema includes the other two schemas, so protobuf will deserialize everything once you deserialize the Envelope. – Carsten Hoffmann Oct 23 '15 at 15:00
  • 1
    I made a small test project and did a few tests and after a few mistakes i got it working. Thanks for the help, i appreciate it! – Tinus Tate Oct 23 '15 at 17:23