Instructional Objectives
After participating in this practicum, students are expected to be able to:
- Understanding about multicast Socket.
- Able to create simple programs.
1. Multicast Socket
Multicasting is broader than unicast, multicasting sends data from one host to a different host, but not to everyone, the data only goes to clients who have stated to join a particular multicast group.
In Java, data multicasting uses the java.net.MulticastSocket class, a subclass of java.net.DatagramSocket. MulticastSocket's behavior is very similar to DatagramSocket's. You put your data in a DatagramPacket object that you send and receive with MulticastSocket. The constructor throws a SocketException if the Socket cannot be created. For example:
try {
MulticastSocket ms = new MulticastSocket( );
// send some datagrams...
} catch (SocketException se) {
System.err.println(se);
}
2. Example Program
MulticastSniffer.java
import java.net.*;
import java.io.*;
public class MulticastSniffer {
public static void main(String[] args) {
InetAddress group = null;
int port = 0;
try {
group = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
} catch (Exception ex) {
System.err.println( "Usage: java MulticastSniffer multicast_address port");
System.exit(1);
}
MulticastSocket ms = null;
try {
ms = new MulticastSocket(port);
ms.joinGroup(group);
byte[] buffer = new byte[8192];
while (true) {
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ms.receive(dp);
String s = new String(dp.getData( ));
System.out.println(s);
}
} catch (IOException ex) {
System.err.println(ex);
} finally {
if (ms != null) {
try {
ms.leaveGroup(group);
ms.close( );
} catch (IOException ex) {
}
}
}
}
}
MulticastSender.java
import java.net.*;
import java.io.*;
public class MulticastSender {
public static void main(String[] args) {
InetAddress ia = null;
int port = 0;
byte ttl = (byte) 1;
try {
ia = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
if (args.length > 2) ttl = (byte) Integer.parseInt(args[2]);
} catch (Exception ex) {
System.err.println(ex);
System.err.println( "Usage: java MulticastSender multicast_address port ttl");
System.exit(1);
}
byte[] data = "Here's some multicast data\r\n".getBytes( );
DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
try {
MulticastSocket ms = new MulticastSocket( );
ms.joinGroup(ia);
for (int i = 1; i < 10; i++) {
ms.send(dp, ttl);
}
ms.leaveGroup(ia);
ms.close( );
} catch (SocketException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
}
}
}