Java Reference
In-Depth Information
32
33
public ItemQuote decode(DatagramPacket p) throws IOException {
34
ByteArrayInputStream payload =
35
new ByteArrayInputStream(p.getData(), p.getOffset(), p.getLength());
36
return decode(payload);
37
}
38 }
ItemQuoteDecoderBin.java
1. Constants, variables, and constructors: lines 5-13
2. Stream decode: lines 15-31
Wrap the InputStream : line 17
Using the given InputStream , construct a DataInputStream so we can make use of the
methods readLong() and readInt() for reading binary data types from the input.
Read integers: lines 18-20
Read the integers back in the same order they were written out. The readLong()
method reads 8 bytes and constructs a (signed) long using big-endian byte ordering.
The readInt() method reads 4 bytes and does the same thing. Either will throw an
EOFException if the stream ends before the requisite number of bytes is read.
Read flag byte: line 21
The flag byte is next; the values of the individual bits will be checked later.
Read string length: lines 22-24
The next byte contains the length of the encoded string. Note that we use the read()
method, which returns the contents of the next byte read as an integer between 0 and
255 (or
1), and that we read it into an int . If we read it into a byte (which is signed),
we would not be able to distinguish between the case where the length is 255 and
the case where the stream ends prematurely—both would return
1, since the signed
interpretation of the 8-bit binary representation of 255 is
1.
Allocate buffer and read encoded string: lines 25-26
Once we know how long the encoded string is, we allocate a buffer and call readFully() ,
which does not return until enough bytes have been read to fill the given buffer.
readFully() will throw an EOFException if the stream ends before the buffer is filled.
Note the advantage of the length-prefixed String representation: bytes do not have to
be interpreted as characters until you have them all.
Check flags: lines 29-30
The expressions used as parameters in the call to the constructor illustrate the stan-
dard method of checking whether a particular bit is set (equal to 1) in an integer type.
3. Packet decode: lines 33-37
Simply wrap the packet's data in a ByteArrayInputStream and pass to the stream-decoding
method.
Search WWH ::




Custom Search