bytesWeHaveBeenReading = 6; // 6 bytes will be removed from buffer
String handShake = new String(dst);
if (!handShake.equals("STP/1\n")) {
close();
connectionHandler.onException(
new CommunicationException("Expected STP/1, got: " + handShake));
}
setState(State.EMPTY);
connectionHandler.onHandshake(true);
}
break;
case EMPTY: // read 4 byte header: STP/0
if (buffer.limit() >= 4) {
byte[] headerPrefix = new byte[4];
buffer.get(headerPrefix);
buffer.position(0);
bytesWeHaveBeenReading = 4;
ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
if (stpPrefix.equals(incomingPrefix)) {
setState(State.STP);
/*
if(buffer.hasRemaining()){
buffer.compact();
readMessage(buffer, buffer.position(), true);
} else {
buffer.clear();
}
*/
} else {
close();
connectionHandler.onException(
new CommunicationException("Expected empty header"));
}
}
break;
case STP:
// Try to read size
buffer.position(0);
if (buffer.limit() <= 0) {
logger.finest("STP: Empty buffer");
break;
}
int messageSize = readRawVarint32(buffer);// read part of buffer
bytesWeHaveBeenReading = buffer.position();
buffer.position(0);
// If we got size, read more, if not just leave it!
if (buffer.limit() >= bytesWeHaveBeenReading + messageSize) {
buffer.position(bytesWeHaveBeenReading);
// Read type and Payload!
int messageType = buffer.get();
bytesWeHaveBeenReading += 1;
byte[] payload = new byte[--messageSize];
buffer.get(payload);
buffer.position(0);
bytesWeHaveBeenReading += messageSize; // 32 bits = 4 bytes :-)
setState(State.EMPTY);
try {
processMessage(messageType, payload);
} catch (IOException e) {
close();
connectionHandler.onException(new CommunicationException(
"Error while processing the message: " + e.getMessage()));
}
} else {
// 4 + messageSize because of the int at the beginning
logger.finest(String.format("Tried to read a message and expected %d bytes, but got %d",