1 package Test; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.InetAddress; 6 import java.net.MulticastSocket; 7 import java.util.Scanner; 8 9 10 public class GuangboSrc { 11 12 /** 13 * @param args 14 * @throws IOException 15 */ 16 public static void main(String[] args) throws IOException { 17 // 创建广播地址 18 InetAddress ip=InetAddress.getByName("230.0.0.1"); 19 // 将创建的广播加入到广播组中 20 21 MulticastSocket multicastSocket=new MulticastSocket(55555); 22 multicastSocket.joinGroup(ip); 23 // 创建广播的数据包 24 System.out.println("请输入要广播的内容:"); 25 Scanner scan=new Scanner(System.in); 26 String str=scan.next(); 27 byte[]b=str.getBytes(); 28 DatagramPacket pancket =new DatagramPacket(b, b.length, ip,55555); 29 // 发送广播 30 multicastSocket.send(pancket); 31 } 32 33 }
1 package Test; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.InetAddress; 6 import java.net.MulticastSocket; 7 import java.net.UnknownHostException; 8 9 public class GuanagboDes { 10 // 接受广播 11 public static void main(String[] args) throws IOException { 12 // TODO Auto-generated method stub 13 // 广播地址 14 InetAddress ip=InetAddress.getByName("230.0.0.1"); 15 // 将广播地址加入到广播组中 16 MulticastSocket multicastSocket=new MulticastSocket(55555); 17 multicastSocket.joinGroup(ip); 18 19 // 接收数据报 20 byte[]b=new byte[1024]; 21 DatagramPacket packet =new DatagramPacket(b,b.length); 22 // 接受广播 23 multicastSocket.receive(packet); 24 // 展示广播内容 25 String str=new String(packet.getData(),0,packet.getLength()); 26 System.out.println("接受到的广播信息是:"+str); 27 28 29 } 30 31 }