I'm implementing a client/server app using JSON (as String) via TCP/IP.
String --> Packet --> byte[] --> tcp/ip --> byte[] --> Packet --> String
The String will be put into a Packet
and sent via TCP/IP.
This way I can simply send a Packet
by getting its raw byte[]
and send it into the TCP/IP socket. On the other side I can simply create a new Packet
by putting the received byte[]
into a Packet
again.
I'm asking you if the Packet class looks okay and if there is anything else wrong with it.
public class Packet {
private final String content;
private final byte[] raw;
private static final int LENGTH_OFFSET = 2;
public Packet (byte[] data) {
if (data == null) {
throw new IllegalArgumentException("data may not be null");
}
if (data.length < 2) {
throw new IllegalArgumentException("invalid data lenght (must be at least two byte)");
}
byte[] lengthByte = new byte[2];
System.arraycopy(data, 0, lengthByte, 0, LENGTH_OFFSET);
int contentLength = getLength(lengthByte);
if (contentLength > data.length-LENGTH_OFFSET) {
throw new IllegalArgumentException("corrupted data - length > data");
}
raw = new byte[contentLength];
System.arraycopy(data, LENGTH_OFFSET, raw, 0, contentLength);
content = new String(raw);
}
public Packet (String cnt) {
if (cnt == null) {
throw new IllegalArgumentException("content may not be null");
}
if (cnt.length() < 0) {
throw new IllegalArgumentException("content must not be empty");
}
content = cnt;
int contentLength = content.length();
byte[] lengthByte = getLength(contentLength);
byte[] stringData = content.getBytes();
raw = new byte[contentLength + LENGTH_OFFSET];
System.arraycopy(lengthByte, 0, raw, 0, LENGTH_OFFSET);
System.arraycopy(stringData, 0, raw, LENGTH_OFFSET, contentLength);
}
private static byte[] getLength(int length) {
if (length > 0xFFFF) {
throw new IllegalArgumentException("data is too long");
}
byte high = trimSignum((length & 0xFF00) >> 8);
byte low = trimSignum((length & 0xFF));
return new byte[] {high, low};
}
private static byte trimSignum(int byteWithSignum) {
if (byteWithSignum > 127) {
return (byte)(0xFF - byteWithSignum);
}
return (byte)byteWithSignum;
}
public String getContent() {
return content;
}
public byte[] getRaw() {
return raw;
}
private static int getLength(byte[] lb) {
int high = (lb[0] & 0xFF) << 8;
int low = (lb[1] & 0xFF);
return high + low;
}
}