简体   繁体   English

关闭套接字会关闭流吗?

[英]Does closing the socket close the stream?

  1. I am working in a legacy java application, In many files, socket and streams are used, where sockets are getting closed but not the streams, is this necessary to close all the streams before closing the socket. 我正在使用遗留的Java应用程序,在许多文件中,使用套接字和流,其中套接字正在关闭而不是流,这是在关闭套接字之前关闭所有流所必需的。 because I am getting "too many open files error", is this error because of not closing the streams..... 因为我收到“太多的打开文件错误”,这个错误是因为没有关闭流.....

  2. closing the socket will automatically close the streams also? 关闭套接字会自动关闭流吗?

From the Socket Javadoc : 来自Socket Javadoc

Closing this socket will also close the socket's InputStream and OutputStream . 关闭此套接字也将关闭套接字的InputStreamOutputStream

So generally speaking, closing the socket should be enough to close both streams it created. 所以一般来说,关闭套接字应该足以关闭它创建的两个流。

Your "too many open files error" is most likely caused by something else. 您的“太多打开文件错误”很可能是由其他原因造成的。

Closing any one of those closes the other two, but you should close the outermost output stream (or Writer ) that you have wrapped around the socket. 关闭其中任何一个会关闭另外两个,但是您应该关闭已经缠绕在套接字上的最外面的输出流(或Writer )。 That closes the input stream and the socket. 这将关闭输入流和套接字。 If you don't close the outermost output stream yourself, it won't get flushed, and so you can lose data if there is a buffered outpput stream or writer in the stack. 如果您没有自己关闭最外面的输出流,它将不会被刷新,因此如果堆栈中有缓冲的输出流或写入器,您可能会丢失数据。 You could also close the socket itself in a finally block to be sure: in fact lack of finally blocks may well be the cause of your problem. 您还可以在finally块中关闭套接字本身以确保:实际上缺少finally块可能是导致问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM