Java网络协议多播

Sender.java

import java.io.IOException; import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Date;
 
public class Sender {

   public static void main(String[] args) {
      try {
        InetAddress address = InetAddress.getByName("228.5.6.7");
        byte[] b = new Date().toString().getBytes();
        DatagramPacket dp = new DatagramPacket(b, b.length, address, 9999);
        MulticastSocket mcs = new MulticastSocket();
        mcs.send(dp);
        mcs.close();
      } catch (UnknownHostException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
   }
}


Receive01.java 

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class Receive01 {
   public static void main(String[] args) {
      try {
        MulticastSocket mcs = new MulticastSocket(9999);
        InetAddress address = InetAddress.getByName("228.5.6.7");
        mcs.joinGroup(address);
        byte[] buff = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buff, buff.length);
        mcs.receive(dp);
        byte[] b = dp.getData();
        int len = dp.getLength();
        System.out.println("接受者1");
        System.out.write(b, 0, len);
        mcs.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
   }
}