简体   繁体   中英

Java.NIO on Write confusion

I have a confusion on the onWrite method of Java NIO, when the selector is ready to write should I:

1: Register/Change a OP_Write

2: If Write returns 0 what should I do?

3: After writing should I Register or Change ops?

The channel is set to Non-Blocking

....onAccept register OP_READ

public void onWrite()
{
            ByteBuffer bb = ByteBuffer.wrap(msg.encode());

            while(bb.remaining()!= 0){
                int ret = socketChannel.write(bb);

                if(ret == 0){

                    //Should I register or should I change op?

                    //socketChannel.register(selector, SelectionKey.OP_WRITE, null);

                    //selectionKey.interestOps(SelectionKey.OP_WRITE);
                }
            }

            //Is it necessary to change op or re-register Read or 0

            //socketChannel.register(selector, SelectionKey.OP_READ, null);
            //selectionKey.interestOps(SelectionKey.OP_READ);
            //selectionKey.interestOps(0);
}   

I'm trying to accomplish the lowest latency possible. And the channel will not echo back, it will just read or write.

when the selector is ready to write should I:

1: Register/Change a OP_Write

It's already registered. That doesn't make sense.

2: If Write returns 0 what should I do?

Register OP_WRITE.

3: After writing should I Register or Change ops?

If it doesn't return zero, deregister OP_WRITE.

The channel is set to Non-Blocking

Of course, otherwise you couldn't register anything.

Basically you have the entire question back to front. You should only register OP_WRITE in case (2). Not all the time. Just write whenever you have something to write, and then look for case 2. Then, when OP_WRITE fires, write and look for case 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM