MulticastSocket describes a socket for the client or server side of a UDP-based multicasting session.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class Main {
final static int PORT = 10000;
public static void main(String[] args) {
try (MulticastSocket mcs = new MulticastSocket()) {
InetAddress group = InetAddress.getByName("1.0.0.1");
byte[] dummy = new byte[0];
DatagramPacket dgp = new DatagramPacket(dummy, 0, group, PORT);
int i = 0;
while (true) {
byte[] buffer = ("line " + i).getBytes();
dgp.setData(buffer);
dgp.setLength(buffer.length);
mcs.send(dgp);
i++;
}
} catch (IOException ioe) {
System.err.println("I/O error: " + ioe.getMessage());
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class Main {
final static int PORT = 10000;
public static void main(String[] args) {
try (MulticastSocket mcs = new MulticastSocket(PORT)) {
InetAddress group = InetAddress.getByName("1.0.0.1");
mcs.joinGroup(group);
for (int i = 0; i < 10; i++) {
byte[] buffer = new byte[256];
DatagramPacket dgp = new DatagramPacket(buffer, buffer.length);
mcs.receive(dgp);
byte[] buffer2 = new byte[dgp.getLength()];
System.arraycopy(dgp.getData(), 0, buffer2, 0, dgp.getLength());
System.out.println(new String(buffer2));
}
mcs.leaveGroup(group);
} catch (IOException ioe) {
System.err.println("I/O error: " + ioe.getMessage());
}
}
}