Java – is it necessary to close the I / O stream created from the socket IO stream when the socket is closed?
•
Java
private val in = new BufferedReader(new InputStreamReader(con.getInputStream()))
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() }
If you create any IO streams or readers / writers from the input or output streams of the socket, do you need to close them before or after the socket is closed?
Solution
You should close the outermost OutputStream or writer created from the socket output stream This will refresh the stream and close the socket and its input stream Closing any other aspect of the socket, such as its direct output stream, its input stream or anything around it, or the socket itself, does most but not all: in particular, closing the input stream before the output stream prevents the output stream from being refreshed in your example, so data may be lost
It is always redundant to call shutdowninput () or shutdownoutput () immediately before shutdown
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码