Note that there are some explanatory texts on larger screens.

plurals
  1. POUnwanted nul characters preceding bytes from TCP socket read using DataInputStream
    primarykey
    data
    text
    <p>I'm writing an Android app that involves connecting to a TCP server (that I also wrote) and sending/receiving text from it. Right now I have a bug in my final read (client-side). </p> <p>When I use the debugger in Eclipse, it shows that I am receiving all the bytes that are sent, but for certain pieces of text, if I'm expecting <em>n</em> bytes, I'll get the first <em>n - k</em>, some <em>m</em> NUL bytes, and then the final <em>k - m</em> meaningful bytes. If I'm interpreting the problem correctly, Java is seeing the huge amount of 0s and deciding that there's nothing useful to be read after (the debugger shows the byte array and the string that it translates to, but then throws it away if I try to inspect it further). </p> <p>How can I ignore the massive influx of NUL and just read the important stuff?</p> <pre><code>// 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 &lt; bytesReceived &amp;&amp; bytesReceived &lt; count) { bytesThisTime = dis.read(received, 0, count); if (bytesThisTime &lt;= 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(); </code></pre> <p>Here is the server code that is doing the writing:</p> <pre><code> // 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(); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload