Search code examples
javanetwork-programmingnio

Once end-of-stream is reached, should the connection explicitly be closed?


I am writing some networking code in NIO.

ByteBuffer buf = ByteBuffer.allocate(Hub.getBufferSize());
int read = channel.read(buf);
if (read == -1) {
    client.disconnect();
    return;
} else if (read == 0) {
    return;
}

I know that is a read returns -1, that means that the end of the connection's stream has been reached. But does that mean that the connection to that client is now over? Furthermore, should the server explicitly close the channel once the end-of-stream is reached, or is it redundant?

Thanks.


Solution

  • I know that is a read returns -1, that means that the end of the connection's stream has been reached. But does that mean that the connection to that client is now over?

    It's the same thing. These aren't two different concepts, such that one of them implies the other. It's the same thing.

    Furthermore, should the server explicitly close the channel once the end-of-stream is reached

    Yes.

    If you don't close it, it is a socket leak and a memory leak.

    or is it redundant?

    Certainly not. See above. Also, if you don't close it, you will keep getting OP_READ on it and keep reading -1 from it. Just wasting time.