我在服务器端有以下代码:
服务器端:
ServerSocket listenTransferSocket = new ServerSocket(6000);
Socket connectionTransferSocket = listenTransferSocket.accept();
DataOutputStream outTransferToClient =
new DataOutputStream(connectionTransferSocket.getOutputStream());
{
....................... (Some code)
.......................
}
outTransferToClient.write(fileInBytes,0,numOfBytes);
System.out.println("File send");
**// outTransferToClient.close();**
BufferedReader inFromClientR =
new BufferedReader(new InputStreamReader(connectionTransferSocket.getInputStream()));客户端:
Socket fileTransferSocket = new Socket("localhost",6000);
DataInputStream in = new DataInputStream(new BufferedInputStream(
fileTransferSocket.getInputStream()));
OutputStream out = new FileOutputStream(new File("./TransferedFiles/"+fileName));
byte[] by = new byte[numOfBytes];
while ((read = in.read(by, 0, numOfBytes)) != -1) {
out.write(by,0,read);
}
DataOutputStream outToServerR =
new DataOutputStream(fileTransferSocket.getOutputStream());
System.out.println("checkC");
outToServerR.writeBytes("Transfer completed \n");当我尝试打开BufferedReader时,如果我关闭它,我会得到以下异常: outTransferToClient.close();
Exception in thread "main" java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:788)
at Server.main(Server.java:92)如果我不这样做,客户端上的while循环永远不会停止..有什么帮助吗?
发布于 2013-04-04 16:23:48
DataOutputStream扩展了具有close()方法的FilterOutputStream
来自docs
Closes this output stream and releases any system resources associated with the stream.
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.此外,在finally块中使用close()这样的方法总是一种很好的做法
发布于 2013-04-04 16:25:54
是的,关闭一个DataOutputStream也会关闭底层的OutputStream。DataOutputStream#close()的Javadoc声明:
FilterOutputStream的close方法调用其flush方法,然后调用其基础输出流的close方法。
另外,Javadoc for Socket声明当您关闭Socket的inputStream或outputStream时,它也会关闭相关的套接字。
因此,在关闭包装了套接字的两个流的DataOutputStream之后,不能重用该套接字。
https://stackoverflow.com/questions/15805971
复制相似问题