开发者

Java Selector select() always returns the last read key

I am trying to write a TCP server that reads data sent by the client. I want to keep the client connection open after the read to be able to read any subsequent data sent.

The code I am executing is below :

    while(true) {
        try {
            int keysSelected = selector.select();

            System.out.println("keysSelected = " + keysSelected);
            if (keysSelected < 1) {
                continue;                    
            }
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }


        Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();

        while(keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            keyIterator.remove();

            if (key.isAcceptable()) {
                processAcceptRequest(selector, key);
            } else if (key.isReadable()) {
                processQueryRequest(key);
            }
        }
    }

The problem I am experiencing is that before any clients have connected, the select call on the selector blocks. After the first client connects and writes data to the server, select continuously returns a OP_READ key, even though there is no data to read? What am I doing wrong?

The code for the read is :

private void processQ开发者_运维问答ueryRequest(SelectionKey key) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(32);

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

    try {
        byteBuffer.clear();

        while(clientChannel.read(byteBuffer) > 0) {
            byteBuffer.flip();

            Charset charset = Charset.forName("UTF-8");
            CharBuffer charBuffer = charset.decode(byteBuffer);

            System.out.println(charBuffer.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Regards Brian


You need to call compact() after you call flip() and process the data you get. You're never doing that, so you're filling the buffer, so read() is returning zero, so you are returning to the select() loop, but there is still pending data in the socket receive buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜