我遇到了一个新的问题,涉及我的安卓应用程序。 SocketChannel
告诉我它 isReadable()
,但是没有可读取的内容。
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);
}
}
}
我在onProgressUpdate
中调用所需的函数。这是一个WebSocket
应用程序,因此我需要发送和接收握手。使用此while循环可以发送和接收握手。首先是SelectionKey.isWriteable()
和握手发送,然后是SelectionKey.isReadable()
和握手读取。但是,SelectionKey.isReadable()
仍然为true。现在调用普通的读取函数(而不是readHandshake
函数),但没有内容可读。以下是我的读函数的代码:
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;
}
现在它卡在了一个无限的while循环中。remainingBytes永远不会小于0,因为没有内容可读取,而bytesRead保持为0。
我的问题是,为什么当没有内容可读取时isReadable为true?