p. 342, Example 13-3: In Java 1.1 the reuse of the same
DatagramPacket
object dp
causes the
UDPDiscardServer
to act
unexpectedly on at least some platforms.
(Exact details appeuar to be dependent on native code.)
dp
is initialized to a length of 65,507 bytes but
the DatagramSocket.receive()
method resets this the length to reflect
the number of data bytes received. When dp
is reused, its length
has been reset to a new and potentially smaller value.
This seems to be something that changed from 1.0 to 1.1. However,
the example can be written in a fashion that supports all cases in both Java 1.0 and 1.1
by moving the line that constructs the DatagramPacket
into the while
loop.
import sun.net.*;
import java.net.*;
import java.io.*;
public class MulticastSniffer {
public static void main(String[] args) {
InetAddress ia = null;
byte[] buffer = new byte[65509];
int port = 0;
// read the address from the command line
try {
try {
ia = InetAddress.getByName(args[0]);
}
catch (UnknownHostException e) {
ia = InetAddressFactory.newInetAddress(args[0]);
}
port = Integer.parseInt(args[1]);
} // end try
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java MulticastSniffer MulticastAddress port");
System.exit(1);
}
try {
MulticastSocket ms = new MulticastSocket(port);
ms.joinGroup(ia);
while (true) {
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ms.receive(dp);
String s = new String(dp.getData(), 0, 0, dp.getLength());
System.out.println(s);
}
}
catch (SocketException se) {
System.err.println(se);
}
catch (IOException ie) {
System.err.println(ie);
}
}
}
p. 344: Example 13-4, MulticastSender, is correct but it could be simpler. It does not need to specify a port because it is only sending, not receiving.