Java Reference
In-Depth Information
RecvUDPMulticast.java
0 import java.net.*; // for MulticastSocket, DatagramPacket, and InetAddress
1 import java.io.*;
// for IOException
2
3 public class RecvUDPMulticast implements ItemQuoteTextConst {
4
5
public static void main(String[] args) throws Exception {
6
7
if (args.length != 2) // Test for correct # of args
8
throw new IllegalArgumentException("Parameter(s): <Multicast Addr> <Port>");
9
10
InetAddress address = InetAddress.getByName(args[0]); // Multicast address
11
if (!address.isMulticastAddress()) // Test if multicast address
12
throw new IllegalArgumentException("Not a multicast address");
13
14
int port = Integer.parseInt(args[1]); // Multicast port
15
16
MulticastSocket sock = new MulticastSocket(port); // Multicast receiving socket
17
sock.joinGroup(address);
// Join the multicast group
18
19
// Create and receive a datagram
20
DatagramPacket packet = new DatagramPacket(
21
new byte[MAX_WIRE_LENGTH], MAX_WIRE_LENGTH);
22
sock.receive(packet);
23
24
ItemQuoteDecoder decoder = new ItemQuoteDecoderText(); // Text decoding
25
ItemQuote quote = decoder.decode(packet);
26
System.out.println(quote);
27
28
sock.close();
29
}
30 }
RecvUDPMulticast.java
The only significant difference between our multicast and unicast receiver is that the
multicast receiver must join the multicast group by supplying the desired multicast address.
The topic's Web site also contains another example of a sender and receiver multicast pair.
MulticastImageSender.java transmits a set of images (JPEG or GIF) specified on the command
line, in three-second intervals. MulticastImageReceiver.java receives each image and displays
it in a window.
Multicast datagrams can, in fact, be sent from a DatagramSocket by simply using a
multicast address. You can test this by using SendUDP.java (see page 57) to send to the multicast
receiver. However, a MulticastSocket has a few capabilities that a DatagramSocket does not,
 
Search WWH ::




Custom Search