簡體   English   中英

套接字編程:輸入流陷入循環 - read() 始終返回 0

[英]Socket Programming : Inputstream Stuck in loop - read() always return 0

服務器端代碼

public static boolean sendFile() {
        int start = Integer.parseInt(startAndEnd[0]) - 1;
        int end = Integer.parseInt(startAndEnd[1]) - 1;
        int size = (end - start) + 1;

        try {
            bos = new BufferedOutputStream(initSocket.getOutputStream());
            bos.write(byteArr,start,size);
            bos.flush();
            bos.close();
            initSocket.close();
            System.out.println("Send file to : " + initSocket);
        } catch (IOException e) {
            System.out.println(e.getLocalizedMessage());
            disconnected();
            return false;
        }

        return true;
    }

客戶端

public boolean receiveFile() {
        int current = 0;

        try {
            int bytesRead = bis.read(byteArr,0,byteArr.length);
            System.out.println("Receive file from : " + client);
            current = bytesRead;
            do {
                 bytesRead =
                 bis.read(byteArr, current, (byteArr.length-current));
                 if(bytesRead >= 0) current += bytesRead;
            } while(bytesRead != -1);
            bis.close();
            bos.write(byteArr, 0 , current);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            System.out.println(e.getLocalizedMessage());
            disconnected();
            return false;
        }
        return true;

    }

客戶端是多線程,服務器端不使用多線程。 我只是粘貼了一些有問題的代碼,如果您想查看所有代碼,請告訴我。

調試代碼后,我發現如果我將最大線程設置為任何,然后第一個線程總是卡在這個循環中。 bis.read(....)總是返回 0。雖然,服務器關閉了 stream 並且它沒有脫離循環。 我不知道為什么......但是另一個線程工作正常。

do {
     bytesRead =
     bis.read(byteArr, current, (byteArr.length-current));
     if(bytesRead >= 0) current += bytesRead;
} while(bytesRead != -1);

當你給它一個沒有剩余空間的緩沖區時,read() 將返回 0。 (這里似乎就是這種情況)

我建議您使用 DataInputStream.readFully() 為您執行此操作。

dis.readFully(byteArr); // keeps reading until the byte[] is full.

如果您只寫入大字節 [] 或只寫入一條數據,則使用緩沖 Stream 只會增加開銷。 你不需要它。

順便說一句:當您調用 close() 時,它會為您調用 flush()。

您的輸入文件有多大(您發送的那個?)以及“byteArr”有多大? 此外,當您檢查讀取了多少字節時,您已經調用了 bis.read(..) 兩次:

    int bytesRead = bis.read(byteArr,0,byteArr.length);

您可能想要讀取/發送大於緩沖區的文件,因此您可能想要執行以下操作:

        byte [] buffer = new byte[4096];
        int bytesRead;
        int totalLength = 0;

        while(-1 != (bytesRead = is.read(buffer))) {
            bos.write(buffer, 0, bytesRead);
            totalLength += bytesRead;
        }
        bos.close();
        is.close();

"is" 是一個普通的 InputStream,Peter 是對的,你不需要緩沖它。

暫無
暫無

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

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