有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java一旦到达endofstream,是否应该显式关闭连接?

我正在用NIO编写一些网络代码

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

我知道这是一个read returns-1,这意味着已经到达连接流的末尾。但这是否意味着与该客户机的连接现在已结束?此外,一旦到达流的末尾,服务器是否应该显式关闭通道,或者是冗余的

谢谢


共 (2) 个答案

  1. # 1 楼答案

    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?

    当然不是。见上文。此外,如果不关闭它,您将继续获取它的OP_READ,并继续从中读取-1。只是浪费时间

  2. # 2 楼答案

    一旦流关闭,就不可能重新打开它。为了避免可能的资源泄漏,显式关闭总是一个好主意