清單 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 多播的對等點發現需要什么。要使它有用,我們需要一個功能不僅限于發送和接收包的軟件組件。理想情況下,這個組件將了解它所接收的包的源對等點,并適當地丟棄一些信息,這些信息是關于那些它認為已經消失、死亡或以其它方式離去的對等點的。