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 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.这将刷新流并关闭套接字及其输入流.关闭套接字的任何其他方面,例如它的直接输出流,它的输入流或其周围的任何东西,或者套接字本身,完成了大部分但不是全部:特别是,在输出流之前关闭输入流在您的示例中,防止输出流被刷新,因此可能会丢失数据.