0

我在服务器端有这个代码:

服务器端:

 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循环永远不会停止..有什么帮助吗????

4

2 回答 2

1

close()DataOutputStream 扩展了具有方法的 FilterOutputStream

来自文档

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-04T08:23:47.943 回答
0

是的,关闭 a也会DataOutputStream关闭底层证券OutputStream。状态的 Javadoc DataOutputStream#close()

FilterOutputStream 的 close 方法调用其 flush 方法,然后调用其底层输出流的 close 方法。

另外,Javadoc forSocket声明当您关闭SocketsinputStreamoutputStream时,它也会关闭关联的套接字。

DataOutputStream因此,在关闭包装其任何一个流的内容后,您将无法重用该套接字。

于 2013-04-04T08:25:54.407 回答