Java Reference
In-Depth Information
RecvUDP.java
0 import java.net.*; // for DatagramSocket and DatagramPacket
1 import java.io.*;
// for IOException
2
3 public class RecvUDP implements ItemQuoteTextConst {
4
5
public static void main(String[] args) throws Exception {
6
7
if (args.length != 1 && args.length != 2) // Test for correct # of args
8
throw new IllegalArgumentException("Parameter(s): <Port> [<encoding>]");
9
10
int port = Integer.parseInt(args[0]);
// Receiving Port
11
12
DatagramSocket sock = new DatagramSocket(port); // UDP socket for receiving
13
ItemQuoteDecoder decoder = (args.length == 2 ?
// Which encoding
14
new ItemQuoteDecoderText(args[1]) :
15
new ItemQuoteDecoderText() );
16
17
DatagramPacket packet = new DatagramPacket(
18
new byte[MAX_WIRE_LENGTH], MAX_WIRE_LENGTH);
19
sock.receive(packet);
20
21
ItemQuote quote = decoder.decode(packet);
22
System.out.println(quote);
23
24
sock.close();
25
}
26 }
RecvUDP.java
3.5
Wrapping Up
We have seen how Java data types can be encoded in different ways, and how messages can
be constructed from various types of information. You may be aware that recent versions of
Java include serialization capabilities—the Serializable and Externalizable interfaces—which
provide for instances of supporting Java classes to be converted to and from byte sequences
very easily. It might seem that having these interfaces available would eliminate the need for
what has been described above, and that is to some extent true. However, it is not always the
case, for a couple of reasons.
First, the encoded forms produced by Serializable may not be very ecient. They may
include information that is meaningless outside the context of the Java Virtual Machine (JVM),
and may also incur overhead to provide flexibility that may not be needed. Second, Serializable
and Externalizable cannot be used when a different wire format has already been specified—
 
Search WWH ::




Custom Search