怎么java nio调用read时仍然是阻塞的呢?

ilovemeimei 2008-09-25 02:09:36


我设想中,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);
}

我现在需要的是一个非阻塞读取的函数,改怎么办呢?什么地方弄错了呢?不想在起线程了。
...全文
170 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
哈库纳玛塔塔 2008-09-25
  • 打赏
  • 举报
回复
Socket非阻塞,得使用 回调函数把?

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧