importjava.io.IOException;
importjava.net.DatagramPacket;
importjava.net.InetAddress;
importjava.net.MulticastSocket;
publicclassMulticastSenderFirst{
static StringipAddr ="224.0.0.1";
staticintport = 8888;
privateInetAddressaddress;
public MulticastSenderFirst()throwsIOException{
address = InetAddress.getByName(ipAddr);
}
publicvoid run(){
intindex=1;
try(MulticastSocketsocket = newMulticastSocket(port)) {
while (true){
String sen="///"+(++index);
byte[]output = (sen).getBytes();
System.out.println("Sent:"+output);
socket.send(newDatagramPacket(output,output.length,address,port));
Thread.sleep(5000);
}
}catch (Exceptionex){
ex.printStackTrace();
}
}
publicstaticvoidmain(String[]arg) {
try {
new MulticastSenderFirst().run();
} catch (IOExceptione) {
e.printStackTrace();
}
}
}
importjava.net.DatagramPacket;
importjava.net.InetAddress;
importjava.net.MulticastSocket;
publicclassMulticastReceiverFirst {
static String_ipAddr ="224.0.0.1";
staticint_port = 8888;
publicstaticvoidmain(String[]args) throws Exception{
MulticastSocket socket =newMulticastSocket(_port);
InetAddress address = InetAddress.getByName(_ipAddr);
socket.joinGroup(address);
byte[]input = newbyte[1024];
DatagramPacket inPacket =newDatagramPacket(input,input.length);
while (true){
socket.receive(inPacket);
String recived=new String(input,0,inPacket.getLength());
System.out.println("--->--->:"+recived);
}
}
}