tags:

views:

41

answers:

1

Hi,

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 processQueryRequest(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

A: 

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.

EJP
Unfortunately this doesn't seem to solve the problem. The key for the read is still always returned, even though the result of the read is always -1?
Brian
That means EOS so you should have closed the channel.
EJP