簡體   English   中英

使用DataInputStream從TCP套接字讀取的字節之前的不需要的nul字符

[英]Unwanted nul characters preceding bytes from TCP socket read using DataInputStream

我正在編寫一個Android應用程序,其中涉及連接到TCP服務器(我也寫過)並從中發送/接收文本。 現在,我在最終閱讀中(客戶端)有一個錯誤。

當我在Eclipse中使用調試器時,它表明我正在接收所有發送的字節,但是對於某些文本,如果我期望n個字節,則將獲得前n-k個 ,即m個 NUL字節,然后是最后k-m個有意義的字節。 如果我正確地解釋了問題,那么Java會看到大量的0,並決定在此之后沒有任何有用的信息可以讀取(調試器顯示了字節數組和它轉換為的字符串,但是如果我嘗試了,則將其丟棄進行進一步檢查)。

我該如何忽略NUL的大量涌入,而只閱讀重要內容?

// Find out how many bytes we're expecting back
int count = dis.readInt(); // dis is a DataInputStream
dos.writeInt(count); // dos is a DataOutputStream

// Read that many bytes
byte[] received = new byte[count];
int bytesReceived = 0;
int bytesThisTime = 0;
while (-1 < bytesReceived && bytesReceived < count) {

    bytesThisTime = dis.read(received, 0, count);
    if (bytesThisTime <= 0) break;

    bytesReceived += bytesThisTime;
    String bytesToString = new String(received, 0, bytesThisTime, "UTF-8");
    sb_in.append(bytesToString);
    received = new byte[count];

}
in = sb_in.toString();

這是進行編寫的服務器代碼:

            // Convert the xml into a byte array according to UTF-8 encoding
            // We want to know how many bytes we're writing to the client
            byte[] xmlBytes = xml.getBytes("UTF-8");
            int length = xmlBytes.length;

            // Tell the client how many bytes we're going to send
            // The client will respond by sending that same number back
            dos.writeInt(length);
            if (dis.readInt() == length) {
              dos.write(xmlBytes, 0, length); // All systems go - write the XML
            }

            // We're done here
            server.close();

更換:

String bytesToString = new String(received, "UTF-8");

與:

String bytesToString = new String(received, 0, bytesThisTime, "UTF-8");

基本上, dis.read(received, 0, count)可以返回0到count之間的任意數量的字節。 bytesThisTime告訴您這次讀取了多少字節 但是稍后您將使用整個數組,而不是僅使用實際讀取的部分。

順便說一句,請考慮使用InputStreamReader ,它將為您即時解碼字符串(但count會有不同的語義)。 此外,請通過IOUtils API仔細閱讀。

Java看到了大量的0,並決定在此之后沒有任何有用的東西可以讀取

不。Java根本不查看數據,更不用說做出這樣的語義決策了。

我該如何忽略NUL的大量涌入,而只閱讀重要內容?

沒有“ NUL的大量涌入”可以忽略。 Java不會那樣做,TCP不會那樣做,什么也不做。

您自己的代碼中只有編程錯誤。

我可以無休止地詳細介紹這些內容,但從本質上講,您應該使用DataInoutStream.readFully()而不是嘗試使用您自己的臭蟲纏身的版本來復制它。

暫無
暫無

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

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