我正在使用 Java 套接字 (TCP) 与服务器通信。我的问题是,当套接字关闭时,与套接字关联的输入和输出流会自动关闭吗?这样做安全吗?
2 回答
是的。如果您关闭Socket,
其输入流或输出流,其他两个将自动关闭。
话虽如此,作为一种良好做法,您应该始终关闭您包裹在套接字周围的最外层输出流或写入器,并且可能在 finally 块中关闭套接字本身。这样可以确保最终输出被刷新。如果您使用缓冲的输出流或写入器并且您不这样做,您将丢失缓冲区中的数据。
According to oracle docs -
You should close any streams connected to a socket before you close the
socket itself.
According to this answer "You must close the output stream, so it gets flushed. That closes both the socket and the input stream. Closing any one of those closes the other two. You don't need to close the input stream at all. Strictly speaking for safety's sake you should probably also close the socket itself in a finally block."
You can explicit stop the incoming data from the inputStream as follows
yourSocket.shutdownInput();
This places input stream for the socket at "end of stream". Any data sent to the input stream side of the socket is acknowledged and then silently discarded.You can still send data to the output socket. Again you have to close the output stream and the socket.
Similarly see shutdownOutput.