java.nio学习笔记(2)

 

nio的select()的时候,只要数据通道允许写,每次select()返回的OP_WRITE都是true。所以在nio的写数据里面,我们在每次需要写数据之前把数据放到缓冲区,并且注册OP_WRITE,对selector进行wakeup(),这样这一轮select()发现有OP_WRITE之后,将缓冲区数据写入channel,清空缓冲区,并且反注册OP_WRITE,写数据完成。

这里面需要注意的是,每个SocketChannel只对应一个SelectionKey,也就是说,在上述的注册和反注册OP_WRITE的时候,不是通过channel.register()和key.cancel()做到的,而是通过key.interestOps()做到的。代码如下:

public void write(MessageSession session, ByteBuffer buffer) throws ClosedChannelException {
   SelectionKey key = session.key();
   if((key.interestOps() & SelectionKey.OP_WRITE) == 0) {
    key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
   }
   try {
   writebuf.put(buffer);
   } catch(Exception e) {
    System.out.println("want put:"+buffer.remaining()+", left:"+writebuf.remaining());
    e.printStackTrace();
   }
   selector.wakeup();
}

.....

while(true) {
   selector.select();
   .....
        if(key.isWritable()) {
         MessageSession session = (MessageSession)key.attachment();
         //System.out.println("Select a write");
         synchronized(session) {
          writebuf.flip();
          SocketChannel channel = (SocketChannel)key.channel();
          int count = channel.write(writebuf);
          //System.out.println("write "+count+" bytes");
          writebuf.clear();
          key.interestOps(SelectionKey.OP_READ);
         }
        }
        ......
    }

要点一:不推荐直接写channel,而是通过缓存和attachment传入要写的数据,改变interestOps()来写数据;

要点二:每个channel只对应一个SelectionKey,所以,只能改变interestOps(),不能register()和cancel()。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值