private val in = new BufferedReader(new InputStreamReader(con.getInputStream()))
private val out = new PrintWriter(con.getOutputStream(), true)
try {
while (true) {
if (in.readLine() == null)
throw new IOException("connection reset by peer")
}
} catch {
case e: Exception =>
} finally {
// Is this necessary?
in.close()
out.close()
// Close socket
con.shutdownInput()
con.shutdownOutput()
con.close()
}
如果任何 IO 流或读取器/写入器是从套接字的输入或输出流创建的,是否有必要在套接字关闭之前或之后关闭它们?
最佳答案
If any IO streams or reader/writers is created from socket's input or output stream, is it necessary to close them before or after socket is closed?
您应该关闭从套接字输出流创建的最外层的 OutputStream
或 Writer
。这将刷新流并关闭套接字及其输入流。关闭套接字的任何其他方面,例如它的直接输出流、输入流或围绕它的任何东西,或套接字本身,可以完成大部分但不是全部:具体来说,在输出流之前关闭输入流在您的示例中,防止输出流被刷新,因此可能会丢失数据。
在关闭之前立即调用 shutdownInput()
或 shutdownOutput()
总是多余的。
关于java - 当套接字关闭时,是否有必要关闭从套接字的 IO 流创建的输入/输出流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15405396/