Netty UDP多播无法在Windows上运行

时间:2015-06-30 10:31:17

标签: java udp netty nio multicast

我一直试图让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();
    }
  }

1 个答案:

答案 0 :(得分:0)

在加入组之前发现绑定到多播地址的问题,由于某种原因在Windows上不起作用。不得不更新bootstrap.bind看起来像这样

  

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