Java Reference
In-Depth Information
gramPackets . Each method performs the same function: extracting the information for one
message and returning an ItemQuote instance containing the information.
ItemQuoteDecoder.java
0 import java.io.*; // for InputStream and IOException
1 import java.net.*; // for DatagramPacket
2
3 public interface ItemQuoteDecoder {
4
ItemQuote decode(InputStream source) throws IOException;
5
ItemQuote decode(DatagramPacket packet) throws IOException;
6 }
ItemQuoteDecoder.java
Sections 3.4.1 and 3.4.2 present two different implementations for these interfaces: one using
a text representation, the other, a hybrid encoding.
3.4.1 Text-Oriented Representation
Clearly we can represent the ItemQuote information as text. One possibility is to simply
transmit the output of the toString() method using a suitable character encoding. To simplify
parsing, the approach in this section uses a different representation, in which the values of
itemNumber , itemDescription , and so on are transmitted as a sequence of delimited text fields.
The sequence of fields is as follows:
Item Number Description Quantity Price Discount? In Stock?
The Item Number field (and the other integer-valued fields, Quantity and Price) contain a
sequence of decimal digit characters followed by a space character (the delimiter). The Descrip-
tion field is just the description text. However, because the text itself may include the space
character, we have to use a different delimiter; we choose the newline character, represented
as \n in Java, as the delimiter for this field.
Boolean values can be encoded in several different ways. One possibility is to include the
string "true" or the string "false" , according to the value of the variable. A more compact
approach (and the one used here) is to encode both values ( discounted and inStock ) in a single
field; the field contains the character 'd' if discounted is true, indicating that the item is
discounted, and the character 's' if inStock is true, indicating that the item is in stock. The
absence of a character indicates that the corresponding boolean is false , so this field may be
empty. Again, a different delimiter ( \n ) is used for this final field, to make it slightly easier to
recognize the end of the message even when this field is empty. A quote for 23 units of item
number 12345, which has the description “AAA Battery” and price $14.45, and which is both
in stock and discounted, would be represented as
12345 AAA Battery\n23 1445 ds\n
 
Search WWH ::




Custom Search