How do I implement a multicast client in NIO.2?

僤鯓⒐⒋嵵緔 提交于 2019-12-05 19:19:13

This example works. Note that DatagramChannel.join() requires a NetworkInterface to work.

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
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!