开发者

Issue in reading data from Socket

开发者 https://www.devze.com 2022-12-09 18:31 出处:网络
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 except

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开发者_Go百科 is no loss of data at any time ? Thanks in advance.


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.


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..


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;
 }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号