I have a new problem with my Android app. SocketChanneltells me he is isReadable(), but there is nothing to read.
while(running)
{
int readyChannels = 0;
try {
readyChannels = selector.select();
} catch (IOException e) {
e.printStackTrace();
}
if(readyChannels == 0) continue;
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext())
{
SelectionKey key1 = keyIterator.next();
if(key1.isReadable())
{
publishProgress(1);
}
else if(key1.isWritable())
{
publishProgress(2);
}
else if(!key1.isValid())
{
Log.e("State", "progress error");
publishProgress(3);
}
}
}
I call the necessary functions in onProgressUpdate. This is an application WebSocket, so I need to send and receive a handshake. Sending and receiving a handshake works with this while loop. First SelectionKey.isWriteable(), a handshake is sent , and then a SelectionKey.isReadable()handshake is read. But then SelectionKey.isReadable()it’s still true. Now the function of the normal read function is called (not readHandshake). But there is nothing to read. Here is the code of my read function:
public byte[] read(int nBytes)
{
Log.e("State", "public byte[] read(int nBytes) start");
byte[] resultData = new byte[1024];
ByteBuffer data = ByteBuffer.wrap(resultData);
int remainingBytes = nBytes;
while(remainingBytes >= 0)
{
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = 0;
try {
bytesRead = channel.read(buffer);
} catch (IOException e) {
Log.e("ERROR", "channel read");
}
if(bytesRead < 0)
{
sockState = WebSocketState.WebSocketErrorOccurred;
}
else
{
remainingBytes = remainingBytes - bytesRead;
data.put(buffer.array(), 0, bytesRead);
}
}
Log.e("State", "public byte[] read(int nBytes) done");
return resultData;
}
Now it is stuck in an endless loop. the remaining bytes will never get <0, because there is nothing to read and bytesRead remains 0.
My question is: why isReadable true when there is nothing to read?