怎么java nio调用read时仍然是阻塞的呢?
我设想中,java的nio操作中的read()不是阻塞的,会立刻返回。所以写了下面这个方法:
public byte[] receive() throws IOException{
receiveBuf.clear();
int n = channel.read(receiveBuf);//(1)
if(n==-1)
throw new IOException();
if(n==0)
return new byte[0];
receiveBuf.flip();
byte [] buf = new byte[n];
receiveBuf.get(buf);
return buf;
}
调试时发现,(1)处会一直阻塞,直到有新的数据到来。这是怎么回事啊?我在构造函数里已经把它设为非阻塞的模式了。构造函数如下:
public SocketManager(InetSocketAddress remoteAddress,int timeout,int sendBufSize, int receiveBufSize) throws IOException {
super();
this.remoteAddress = remoteAddress;
this.sendBufSize = sendBufSize;
this.receiveBufSize = receiveBufSize;
sendBuf = ByteBuffer.allocate(sendBufSize);
receiveBuf = ByteBuffer.allocate(receiveBufSize);
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.socket().setSoTimeout(timeout);
}
我现在需要的是一个非阻塞读取的函数,改怎么办呢?什么地方弄错了呢?不想在起线程了。