Does your client know how the byte array size varies?
A well known approach (it needs you manage this also at the server side) is to encapsulate the data inside a packet with the following fields: | TYPE | SIZE | DATA |
so, supposing the client has an open socket connection and instantiate a DataInputStream (dataInputStream = new DataInputStream(socket.getInputStream())
), the client can read the data in a thread which run
method is something like this:
@Override
public void run() {
while(running) {
int pckType = readPacketType();
int pckSize = readPacketSize();
byte[] data = readPacketContent(pckSize);
// do something with data
// you can use Semaphore instances in order to maintains a set of permits if needed
}
}
where
private int readPacketType() {
int result = -1;
byte[] array = new byte[1];
try {
dataInputStream.read(array);
result = (int)array[0];
} catch (IOException ex) {
return -1;
}
return result;
}
private int readPacketSize() {
int result = -1;
byte[] array = new byte[4];
try {
dataInputStream.read(array);
result = ByteBuffer.wrap(array).getInt();
} catch (IOException ex) {
return -1;
}
return result;
}
private byte[] readPacketContent(int contentSize) {
byte[] result = new byte[contentSize];
try {
dataInputStream.read(result);
} catch (IOException ex) {}
return result;
}
noting that I assigned, for example, 1 byte for the TYPE field and 4 byte for the SIZE field
EDIT:
You can use an implementation of the BlockingQueue interface like LinkedBlockingQueue. You can put byte[] of different size and retrieve them coherently (keeping the order and the size). Follows an easy check ;)
LinkedBlockingQueue<byte[]> lbq = new LinkedBlockingQueue<byte[]>();
String str1 = "blablabla";
String str2 = "blabla";
try {
lbq.put(str1.getBytes());
lbq.put(str2.getBytes());
lbq.put(str1.getBytes());
} catch (InterruptedException e) {
e.printStackTrace();
}
byte[] b = null;
int size = lbq.size();
for(int i=0; i<size; i++) {
try {
b = lbq.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(b.length);
}