0
votes

I have a couple of questions regarding a custom binary protocol.

Our server is connected to a CCT (Custom Command Terminal) which is controlled by the user and can send binary commands to this central unit. The communication between the CCT and the server is a standard ethernet socket on a certain port.

All commands and messages in both directions will use the same frame format:

  • STX: 0x02 - byte indicating the start of the command
  • Length: The length of the messages including the STX and length bytes but not the checksum byte
  • Command: The type of command
  • Parameter 1-n: the data bytes for the given command number
  • ChkSm: A checksum byte

When the server receives a message with a valid checksum or a first connection, it will send a single acknowledge byte back.

For the communication, I'm using a standard Java socket with a DataInputStream and DataOutputStream.

  1. How I can correctly read in the bytes from the DataInputStream and cast these back to their original values (integer, booleans, ...). I know there are the readByte(), readShort() and readbyte(byteArr, offsett, length) methods but why would I prefer the one over the other.

  2. readbyte(byteArr, offsett, length) returns the number of bytes read. Why would I use this value is my scenario. What size should the byteArr be as my parameter?

     byte[] responseBytes = new byte[5];
     int bytesRead = 0;
     try {
         bytesRead = mInputStream.read(responseBytes, 0, 4);
     } catch (IOException e1) {
         e1.printStackTrace();
     }
    
  3. When I receive data from the inputstream and I use readByte(), would this be the STX (the start of the command)?

  4. How are binary protocols handled? Is there any best practice on getting started on this? Maybe an example based on what I am trying to achieve?

1
What is value of "single acknowledge byte"?Andreas
The value is: 0x0AVerhelst

1 Answers

1
votes

How I can correctly read in the bytes from the DataInputStream

Don't use DataInputStream. Just use the plain InputStream.

readbyte(byteArr, offsett, length) returns the number of bytes read. Why would I use this value is my scenario. What size should the byteArr be as my parameter?

Since the Length is only a single byte, a command can be at most 256 bytes long (255 + 1 byte ChkSm), so use a byte[256].

The value returned by read(responseBytes) then tells you how many bytes you actually received, so you know whether you got all the bytes (compare with Length).

When I receive data from the inputstream and I use readByte()

You probably wouldn't use read() to read a single byte, only read(responseBytes).

How are binary protocols handled?

Depends on the protocol. There is no single good answer.