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,这意味着已经到达连接流的末尾。但这是否意味着与该客户机的连接现在已结束?此外,一旦到达流的末尾,服务器是否应该显式关闭通道,或者是冗余的
谢谢
# 1 楼答案
是一样的。这不是两个不同的概念,其中一个意味着另一个。是一样的
对
如果你不关闭它,它是一个套接字泄漏和内存泄漏
当然不是。见上文。此外,如果不关闭它,您将继续获取它的
OP_READ
,并继续从中读取-1
。只是浪费时间# 2 楼答案
一旦流关闭,就不可能重新打开它。为了避免可能的资源泄漏,显式关闭总是一个好主意