I’m confused by DataInputStream.read() method which is explained “If no byte is available because the end of the stream has been reached, the value -1 is returned. ” in javadoc/api. With my following code snippet and telegram captured by wireshark, I expected to get “1042000001031640100002829130231911299”(in frame 9) however “104200000103164010000282913023191129910441020”(in frame 9 AND frame 19) is what I got:
int a = 0;
while(( a = in.read())!= -1){
System.out.print(a);
}
Timesync response
Supervisory
In my understanding, when frame 9 ends, we ‘reach the end of stream’, so we get 1042000001031640100002829130231911299(in dec, while in wireshark it’s in hex). But it seems we ‘reach the end of stream’ when socket is closed.
Then how to get only the data in frame 9 (I’ll store it in a byte array)? Can anyone help me?
3
Answers
The notion of frames or packets is a physical, low-level notion of the network protocol.
You can’t choose how sent bytes are grouped in packets, and you can’t get a given number of packets. Only a continuous stream of bytes.
You need an application-level protocol on top of TCP to distinguish your functional messages. They could be lines of text ended with a newline character, or a number of bytes N followed by N bytes, or something like that.
Here’s the javadoc for
read()
, this is what it says:So, in your case, end of
frame
does not mean end of stream as there are more frames into thestream
(yes, end of stream means all the data is transmitted).If you want to read the data for one frame then you can use overloaded version of
read
, e.g.:However, these methods might not read all the bytes. If you know the
length
of a frame then you can write a wrapper aroundread()
and perform an action every timelength
bytes are read.Your understanding is entirely incorrect. End of a frame is not end of stream. End of stream on a socket means the peer has closed the connection.
If you want to read fixed length frames, see
DataInputStream.readFully()
.