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.
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()
andreadbyte(byteArr, offsett, length)
methods but why would I prefer the one over the other.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(); }
When I receive data from the inputstream and I use
readByte()
, would this be the STX (the start of the command)?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?