Multicast Group
In this chapter you will learn:
Joining a Multicast Group
import java.net.InetAddress;
import java.net.MulticastSocket;
//j ava 2 s . c o m
public class Main {
public static void main(String[] argv) throws Exception {
String groupName = "groupName";
int port = 1024;
MulticastSocket msocket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName(groupName);
msocket.joinGroup(group);
}
}
Receiving from a Multicast Group
import java.net.DatagramPacket;
import java.net.MulticastSocket;
// j a v a 2s . co m
public class Main {
public static void main(String[] argv) throws Exception {
MulticastSocket msocket = new MulticastSocket(9999);
byte[] inbuf = new byte[1024];
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
msocket.receive(packet);
// Data is now in inbuf
int numBytesReceived = packet.getLength();
}
}
Multicast Sender
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
//j av a 2s. c o m
public class MainClass {
public static void main(String[] args) throws Exception {
int port = 0;
byte ttl = (byte) 1;
InetAddress ia = InetAddress.getByName("127.0.0.1");
byte[] data = "Here's some multicast data\r\n".getBytes();
DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
MulticastSocket ms = new MulticastSocket();
ms.joinGroup(ia);
for (int i = 1; i < 10; i++) {
ms.send(dp, ttl);
}
ms.leaveGroup(ia);
ms.close();
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Socket