java中用时多久怎么写_在JAVA nio选择器中,我什么时候应该注册“写...

我正在学习Java nio选择器.在我的理解中,我认为使用选择器的步骤是首先注册我的兴趣操作,然后我可以检查准备好的设置,最后可以进行与我的兴趣操作相对应的操作.我不知道为什么在这段代码中,写入过程会在if(key.isReadable()){…}块中发生,但是如果if(key.isWritable){…}不会发生,为什么写入操作不起作用注册?

Iterator keys = sel.selectedKeys().iterator();

while (keys.hasNext()) {

SelectionKey key = (SelectionKey)keys.next();

if (!key.isValid())

continue;

if (key.isAcceptable()) {

// increase the counter

connection++;

// remove accept request

keys.remove();

// ACCEPT: get the server channel

ServerSocketChannel ssc =

(ServerSocketChannel) key.channel();

// init a socket for a client

SocketChannel nsc = ssc.accept();

nsc.configureBlocking(false);

// register the socket for READ

nsc.register(sel, SelectionKey.OP_READ);

}

}

while (count < COUNT_MAX + NUM_CHILD - 1) {

sel.select();

// Get all pending events and iterate

Iterator keys = sel.selectedKeys().iterator();

while ( keys.hasNext() ) {

SelectionKey key = (SelectionKey)keys.next();

keys.remove();

if (!key.isValid())

continue;

if (key.isReadable()) {

// READ: get the channel

SocketChannel nsc = (SocketChannel) key.channel();

// clear buffer for reading

readBuffer.clear();

int nBytes = nsc.read(readBuffer);

if (nBytes == -1) {// Check if the client closed the socket

key.channel().close();

key.cancel();

continue;

}

// Read a message

DataInputStream ist = new DataInputStream (

new ByteArrayInputStream(readBuffer.array()));

String msg = ist.readUTF();

System.out.print(msg + "

");

// Clear the write buffer

writeBuffer.clear();

// Write the counter value on the buffer

count++;

if (count < COUNT_MAX)

writeBuffer.putInt(count);

else

writeBuffer.putInt(-1);

// flip the buffer and write on the channel

writeBuffer.flip();

// Reply to a client

nsc.write(writeBuffer);

}

} // while (key)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值