UDP组播发送端:
1 public static void main(String[] args) throws IOException { 2 DatagramSocket socket = new DatagramSocket(); 3 //组播地址224.0.0.0——239.255.255.255 4 //其中224.0.0.0——224.0.0.255为预留的组播地址 5 // 所以我们使用组播地址要从224.0.1.0开始 6 String s = "Hello,组播"; 7 byte[] bytes = s.getBytes(); 8 InetAddress address = InetAddress.getByName("224.0.1.255"); 9 DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, 1026); 10 11 socket.send(packet); 12 socket.close(); 13 14 15 }
UDP组播接收端:
1 public static void main(String[] args) throws IOException { 2 MulticastSocket socket = new MulticastSocket(1026);//和单播创建邮局不一样注意 3 byte[] bytes = new byte[1024]; 4 DatagramPacket packet = new DatagramPacket(bytes, bytes.length); 5 socket.joinGroup(InetAddress.getByName("224.0.1.255"));//相当于单播中的电脑IP 6 socket.receive(packet); 7 byte[] data = packet.getData(); 8 int length = packet.getLength(); 9 System.out.println(new String(data, 0, length)); 10 11 socket.close(); 12 13 }
需要注意的是:
组播地址224.0.0.0——239.255.255.255 其中224.0.0.0——224.0.0.255为预留的组播地址,所以我们使用组播地址要从224.0.1.0开始