开发者

Sockets and DataInputStream

I am trying to understand this snippet of code

        DataInputStream stream = 
          new DataInputStream(
            new ByteArrayInputStream(messageBuffer));


        int     messageLength   = stream.readInt();
        char    recordType      = (char) stream.readByte();
        byte    padding         = stream.readByte();
        short   numberRecords   = stream.readShort();

messageBuffer is initialised as new byte[32768] as is populated via a Socket.read() method. What i dont understand is once messageLength has been initialised to stream.readInt(), how will the second second statement wo开发者_Go百科rk i.e. recordType?

Wouldnt the first statement read an int from the beginning of the byte array and the next statement read a byte from the beginning of the byte array? How exactly does it know from which point to read the bytes, ints, shorts etc?


From the documentation:

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.

In other words, DataInputStream simply reads from the ByteArrayInputStream, while the latter remembers the current position in the byte array and advances it every time some data has been read.


readX() doesn't read from the beginning of the stream. In fact the term stream is used to denote a sequence of data made available over time. That means subsequent reads from a stream will retrieve different elements.

Think of a stream as a conveyor belt of information rather than an array.


The DataInputStream.read* methods consume bytes from the underlying input stream. In this case the read* methods read the next available bytes provided by the ByteArrayInputStream which will keep track of the current position in the array.


As a side-note, you may want to consider using ByteBuffer.wrap and the various ByteBuffer.read methods:

ByteBuffer msgBuf = ByteBuffer.wrap(messageBuffer);
int messageLength = msgBuf.getInt();
char recordType   = msgBuf.getChar();
...


Socket.read() will read the bytes which are available. The minimum is one byte! The maximum is the buffer size which could have any number of messages in it.

Instead of reading a buffer manually, it is safer, simpler and more efficient to use a DataInputStream/BufferedInputStream.

// create an input stream once per socket.
DataInputStream stream = 
      new DataInputStream(
        new BufferedInputStream(socket.getInputStream()));


int     messageLength   = stream.readInt();
char    recordType      = (char) stream.readByte();
byte    padding         = stream.readByte();
short   numberRecords   = stream.readShort();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜