代码之家  ›  专栏  ›  技术社区  ›  Sundae

如何在NIO.2中实现多播客户端?

  •  3
  • Sundae  · 技术社区  · 11 年前

    使用Java7NIO.2多播客户端的示例是什么样子的?我只能在 MulticastChannel 文档

    1 回复  |  直到 11 年前
        1
  •  4
  •   Sundae    11 年前

    此示例有效。请注意 DatagramChannel.join() 需要 NetworkInterface 工作。

    NetworkInterface ni = NetworkInterface.getByInetAddress(address);
    InetAddress group = InetAddress.getByName("239.255.0.1")
    
    DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
        .setOption(StandardSocketOptions.SO_REUSEADDR, true)
        .bind(new InetSocketAddress(5000))
        .setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
    MembershipKey key = dc.join(group, ni);
    
    ByteBuffer byteBuffer = ByteBuffer.allocate(1500);
    while (true) {
        if (key.isValid()) {
            byteBuffer.clear();
            InetSocketAddress sa = (InetSocketAddress) dc.receive(byteBuffer);
            byteBuffer.flip();
    
            System.out.println("Multicast received from " + sa.getHostString());
    
            // TODO: Parse message
        }
    }