Tuesday 15 February 2011

Java socket - lost bytes and 100% processor power consumption -


I am making a simple socket app connecting to my server via TCP I sometimes read 2 byte values Required, so it's like everything:

  Read public byte [] (int bytes) {byte b [] = new byte [bytes]; {In.read (b) try; // inInputStream properly connected to Socket.getInputStream () return b; } Hold (IOException e) {return tap; }}   

This function should get the number of bytes and return it to the array. The problem is, sometimes it reads a byte until the rest is available and gives strange data.

  byte a [] = read (2); // program is blocked here until some bytes come ... System.out.prntln (a [0]); // Always the right system Out.printline (a [1]); // Unchargable character (probably 0 or -1)   

To add during my quick fix was to check the loop, if there is enough data to read:

  read by public byte [] (int bytes) {byte b [] = new byte [bytes]; When trying (in.available () & lt; bytes); // There's a point in it. Reid (B); Return b; } Hold (IOException e) {return tap; }}   

But this loop is using 100% processor power (a core, in fact), which is very upset. Is there any way to rewrite that function (the ultimate and return value should be exactly the same), then does it work properly?

Thanx in advance :)

Yes your quick correction is a bad idea In, any code using available is probably broken.

How do I do this:

  Read public byte [] throws IOException (byte bits) [byte b [] = new byte [bytes]; Int pos = 0; Whereas (pos & lt; b.length) {int nosRead = in.read (b, pos, b.length - pos); If (nosRead == -1) {return tap; // is not the best idea ... see below} Else {pos + = nosRead; }} Return b; }   

There is no need to "vote" the stream using the available () . There is no need for gold. You only use this fact that read only if only at least one byte is read or if you are fit in the "end of the stream" then only return.


Note that I do not even think that the null has the right to return if your read method fails. It is better to throw exceptions ... or IOException to in.read () call promotion.

This also applies to my rewriting ... I did not want to change the behavior of my code in that respect.

No comments:

Post a Comment