Netty UDP 多播无法在 windows 上工作

Netty UDP multicast not working on windows

几天来,我一直在尝试让 udp 多播在 windows 上运行,但没有成功。这是一个简单的应用程序,它只是加入一个组并写入在 OSX 上工作的控制台,但在 windows 上抛出通道关闭异常。任何帮助将不胜感激。

    public class UDPMulticastTest {

    public void start() throws Exception{
        EventLoopGroup group=new NioEventLoopGroup();
        ChannelGroup allChannels=new DefaultChannelGroup("Test", ImmediateEventExecutor.INSTANCE);
        try{
            Bootstrap b=new Bootstrap();
            b.group(group)
            .channel(NioDatagramChannel.class)
            .option(ChannelOption.SO_BROADCAST,true)
            .handler(new SimpleChannelInboundHandler<DatagramPacket>() {

                @Override
                protected void channelRead0(ChannelHandlerContext arg0, DatagramPacket arg1) throws Exception {
                    String res=arg1.content().toString(CharsetUtil.UTF_8);
                    System.out.println(res);

                }
            });

            InetSocketAddress hostAddress=new InetSocketAddress("239.21.208.200", 58999);
            ChannelFuture channelFuture=b.bind(hostAddress);
            channelFuture.awaitUninterruptibly();
            Channel channel=channelFuture.channel();
            DatagramChannel datagramChannel=(DatagramChannel)channel;
            NetworkInterface multicastNetworkInterface=NetworkInterface.getByName("wlan0"); //used en0 for OSX, 
            datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
            allChannels.add(datagramChannel);
            channel.closeFuture().await();

        }finally{
            group.shutdownGracefully();
        }
    }
    public static void main(String[] args)throws Exception{
       new UDPMulticastTest().start();
    }
  }

发现问题出在加入组之前绑定到多播地址,由于某种原因在 windows 上不起作用。必须将 bootstrap.bind 更新为如下所示

ChannelFuture channelFuture=b.bind(new InetSocketAddress(PORT_NUMBER));