1、服务端
public class UdpMulticastServer { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // 接受组播和发送组播的数据报服务都要把组播地址添加进来 String host = "225.0.0.1";// 多播地址 int port = 9998; int length = 1024; byte[] buf = new byte[length]; MulticastSocket ms = null; DatagramPacket dp = null; try { ms = new MulticastSocket(port); dp = new DatagramPacket(buf, length); // 加入多播地址 InetAddress group = InetAddress.getByName(host); ms.joinGroup(group); System.out.println("监听多播端口打开:"); while (true) { ms.receive(dp); int i; StringBuffer sbuf = new StringBuffer(); for (i = 0; i < 1024; i++) { if (buf[i] == 0) { break; } sbuf.append((char) buf[i]); } System.out.println("收到多播消息:" + sbuf.toString()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } }
2、客户端
public class UdpMulticastClient { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String host = "225.0.0.1";// 多播地址 int port = 9998; String message = "test-multicastSocket"; try { InetAddress group = InetAddress.getByName(host); MulticastSocket s = new MulticastSocket(); // 加入多播组 s.joinGroup(group); DatagramPacket dp = new DatagramPacket(message.getBytes(), message.length(), group, port); while (true) { s.send(dp); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }