一、服务端
public class MulticastServer {
public static void main(String[] args) throws IOException, InterruptedException {
// 组播地址D类Ip地址,地址段224.0.0.0 - 239.255.255.255
InetSocketAddress group = new InetSocketAddress("224.5.6.7", 8888);
MulticastSocket socket = new MulticastSocket();
for (int i = 0; i < 10; i++){
String data = "Hello zz "+ i;
byte[] bytes = data.getBytes();
// 发送数据报
socket.send(new DatagramPacket(bytes, bytes.length, group));
TimeUnit.SECONDS.sleep(2);
}
}
}
二、客户端
public class MulticastClient {
public static void main(String[] args) throws IOException {
InetAddress group = InetAddress.getByName("224.5.6.7");
MulticastSocket socket = new MulticastSocket(8888);
// 加到指定的组里面
socket.joinGroup(group);
byte[] buf = new byte[256];
while (true){
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
// 接受数据报
socket.receive(msgPacket);
String msg = new String(msgPacket.getData());
System.out.println("接收到的数据:" + msg);
}
}
}