tags:

views:

111

answers:

3

Hi, I am facing some problem during reading data from socket If there is some null data in socket stream so the DataInputStream would not read the full data and the so at the receiving end there is exception for parsing data. What is the right way to read the data from socket so there is no loss of data at any time ? Thanks in advance.

+1  A: 

You should post the code being used to read from the socket, but to me the most likely case is that the reading code is incorrectly interpreting a 0 byte as the end of the stream similar to this code

InputStream is = ...;
int val = is.read();
while (0 != (val = is.read()) {
  // do something
}

But the end of stream indicator is actually -1

InputStream is = ...;
int val = is.read();
while (-1 != (val = is.read()) {
  // do something
}

EDIT: in response to your comment on using isavailable(). I assume you mean available() since there is no method on isavailable() InputStream. If you're using available to detect the end of the stream, that is also wrong. That function only tells you how many bytes can be read without blocking (i.e. how many are currently in the buffer), not how many bytes there are left in the stream.

Jherico
i am using isavailable and i read the whole data
Sam97305421562
OK, so post the code,or a minimal example of the code which can duplicate the problem. I said I was speculating and coulnd't be certain without seeing the code.
Jherico
A: 

I personally prefer ObjectInputStream over DataInputStream since it can handle all types including strings, arrays, and even objects.

Yes, you can read an entire object only by 1 line receive.readObject(), but don't forget to type-cast the returned object.

read() mightbe easier since you read the whole thing in 1 line, but not accurate. read the data one by one, like this:

receive.readBoolean()
receive.readInt()
receive.readChar()
etc..
evilReiko
A: 
String finalString = new String("");
int finalSize = remainingData;//sizeOfDataN;
int reclen = 0;
int count_for_breaking_loop_for_reading_data = 0;
boolean  for_parsing_data  = true; 
while(allDataReceived == false) {      
 ByteBuffer databuff = ByteBuffer.allocate(dis.available());
 //   System.out.println("bis.availbale is "+dis.available());
 databuff.clear();
 databuff.flip();
 dis.read(databuff.array());
 String receivedStringN   = trimNull(databuff.array());
 finalString = finalString + receivedStringN;
 System.out.println("final string length "+finalString.length());
 if(finalString.length() == finalSize) {
    allDataReceived = true;
 }
 count_for_breaking_loop_for_reading_data++;
 if(count_for_breaking_loop_for_reading_data > 1500) {
 For_parsing_data =  false;
 Break;
 }
 }
Sam97305421562