简体   繁体   中英

is there any bug about selectionKey.attachment() in java nio?

fun main(args: Array<String>) {
    val selector = Selector.open()
    val sc = SocketChannel.open()
    sc.configureBlocking(false)
    sc.connect(InetSocketAddress(1234))
    val key = sc.register(selector, SelectionKey.OP_CONNECT)
    println("key=$key")
    key.attach(ClientAttachment())

    writeThread(sc)

    while (selector.isOpen) {
        if (selector.select() == 0) continue

        val keys = selector.selectedKeys().iterator()
        while (keys.hasNext()) {
            val key = keys.next()
            println("key=$key")
            println("ac=${key.attachment()}")
            keys.remove()
            if (key.isConnectable) {
                val c = key.channel() as SocketChannel
                while (!c.finishConnect()) {
                    Thread.sleep(100)
                }
                println("连接服务器成功")
                c.register(selector, SelectionKey.OP_READ)
            } else if (key.isReadable) {
                handleRead(key)
            }
        }
    }
}

I create a SocketChannel,and regist it to a selector,and then attach an Object to the key.

when I receive the first OP_CONNECT event,I can get the attachment successfully. but at the next OP_READ event, the attachment() returns null?

why?

c.register(selector, SelectionKey.OP_READ);

This creates a new registration, with a new SelectionKey and a new attachment: in this case null , as you didn't supply one. If you want to preserve the prior attachment, either just call interestOps() with new arguments, or else call register(Selector, int, Object) with the same attachment object as before.

BUT Your connect code is pointless. You put the channel into non-blocking mode, and then you execute essentially a blocking-mode connect the hard way, with sleeps. Just leave the channel in blocking mode, do the connect, then put it into non-blocking mode if you must and start the select loop. But the point of non-blocking, or even NIO for that matter, in a client, has always escaped me, unless you're planning to connect to lots of servers, or one server with lots of connections (like a spider).

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