清单 1. 简单服务器 public class Server { public static void main(String [] arstring) { try { // Create a multicast datagram socket for receiving IP // multicast packets. Join the multicast group at // 230.0.0.1, port 7777. MulticastSocket multicastSocket = new MulticastSocket(7777); InetAddress inetAddress = InetAddress.getByName("230.0.0.1"); multicastSocket.joinGroup(inetAddress); // Loop forever and receive messages from clients. PRint // the received messages. while (true) { byte [] arb = new byte [100]; DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length); multicastSocket.receive(datagramPacket); System.out.println(new String(arb)); } } catch (Exception exception) { exception.printStackTrace(); } } }
清单 2. 简单客户机 public class Client { public static void main(String [] arstring) { try { // Create a datagram package and send it to the multicast // group at 230.0.0.1, port 7777. byte [] arb = new byte [] {'h','e','l','l','o'}; InetAddress inetAddress = InetAddress.getByName("230.0.0.1"); DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length, inetAddress, 7777); MulticastSocket multicastSocket = new MulticastSocket(); multicastSocket.send(datagramPacket); } catch (Exception exception) { exception.printStackTrace(); } } }
java.net 包中的两个类使它运行。java.net.DatagramPacket 类保存了 IP 数据报包中包含的数据。java.net.MulticastSocket 类创建一个调整到一个特定多播组的多播套接字。
发现组件 尽管上述示例是一个很好的 IP 多播的演示,但它没有说明实现基于 IP 多播的对等点发现需要什么。要使它有用,我们需要一个功能不仅限于发送和接收包的软件组件。理想情况下,这个组件将了解它所接收的包的源对等点,并适当地丢弃一些信息,这些信息是关于那些它认为已经消失、死亡或以其它方式离去的对等点的。