Try to find the protocol from the SocketChannel
bytes.
final SelectionKey key = protocolInfo.key;
final SocketChannel socketChannel = (SocketChannel)key.channel();
final ByteBuffer byteBuffer = protocolInfo.byteBuffer;
int loop = 0;
int count = -1;
if (protocolInfo.bytesRead == 0) {
try {
while ( socketChannel.isOpen() &&
((count = socketChannel.read(byteBuffer))> -1)){
if ( count == 0 ){
loop++;
if (loop > 2){
break;
}
continue;
}
}
} catch (IOException ex){
;
} finally {
if ( count == -1 ){
return;
}
protocolInfo.bytesRead = count;
}
}
final int curPosition = byteBuffer.position();
final int curLimit = byteBuffer.limit();
// Rule a - If read length < PROTOCOL_ID.length, return to the Selector.
if (curPosition < TCPConstants.PROTOCOL_SCHEMA.length()){
return;
}
byteBuffer.position(0);
byteBuffer.limit(curPosition);
// Rule b - check protocol id
try {
final byte[] protocolBytes = new byte[TCPConstants.PROTOCOL_SCHEMA.length()];
byteBuffer.get(protocolBytes);
final String incomeProtocolId = new String(protocolBytes);
if (TCPConstants.PROTOCOL_SCHEMA.equals(incomeProtocolId)) {
protocolInfo.protocol = TCPConstants.PROTOCOL_SCHEMA;
protocolInfo.byteBuffer = byteBuffer;
protocolInfo.socketChannel =
(SocketChannel)key.channel();
protocolInfo.isSecure = false;
}
} catch (BufferUnderflowException bue) {
} finally {
byteBuffer.limit(curLimit);
byteBuffer.position(curPosition);
}