skip to Main Content

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

Timesync response

Supervisory

Timesync response

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


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

    Login or Signup to reply.
  2. Here’s the javadoc for read(), this is what it says:

    If no byte is available because the end of the stream has been
    reached, the value -1 is returned.

    So, in your case, end of frame does not mean end of stream as there are more frames into the stream (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.:

    public int read(byte[] b) throws IOException
    
    public int read(byte[] b, int off, int len) throws IOException
    

    However, these methods might not read all the bytes. If you know the length of a frame then you can write a wrapper around read() and perform an action every time length bytes are read.

    Login or Signup to reply.
  3. In my understanding, when frame 9 ends, we ‘reach the end of stream

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search