簡體   English   中英

數據輸入流

[英]DataInputStream

我在服務器端有以下代碼:

服務器端:

 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循環永遠不會停止..任何幫助嗎????

DataOutputStream擴展了具有close()方法的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()的方法始終是一種不錯的做法

是的,關閉DataOutputStream關閉基礎OutputStream DataOutputStream#close()的Javadoc指出:

FilterOutputStream的close方法調用其flush方法,然后調用其基礎輸出流的close方法。

另外, 用於SocketJavadoc指出,當您關閉SocketinputStreamoutputStream ,它還將關閉關聯的套接字。

因此,在關閉包裝了其中一個流的DataOutputStream之后,您將無法重用該套接字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM