Example #1
0
  public void init(ChannelPipelineFactory factory) throws Exception {
    id =
        String.format("%1$020d", Math.abs(new Random(System.currentTimeMillis()).nextLong()))
            .getBytes();

    group = new OioEventLoopGroup();
    connectionlessBootstrap = new Bootstrap();
    connectionlessBootstrap.group(group);
    connectionlessBootstrap.option(ChannelOption.SO_BROADCAST, true);
    connectionlessBootstrap.handler(factory);
    connectionlessBootstrap.channel(OioDatagramChannel.class);
    ;
    datagramChannel =
        (DatagramChannel)
            connectionlessBootstrap.bind(new InetSocketAddress(mcastGroupPort)).sync().channel();
    multicastAddress = new InetSocketAddress(mcastGroupIp, mcastGroupPort);
    NetworkInterface networkInterface =
        NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddress));
    // for (Enumeration nifs = NetworkInterface.getNetworkInterfaces();
    // nifs.hasMoreElements(); )
    datagramChannel.joinGroup(multicastAddress, null); // (NetworkInterface)
    // nifs.nextElement());
    init = true;
    if (debug) factory.debug();
  }
  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioDatagramChannel.class)
          .option(ChannelOption.SO_BROADCAST, true)
          .handler(new QuoteOfTheMomentClientHandler());

      Channel ch = b.bind(0).sync().channel();

      // Broadcast the QOTM request to port 8080.
      ch.write(
              new DatagramPacket(
                  Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                  new InetSocketAddress("255.255.255.255", port)))
          .flush()
          .sync();

      // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
      // response is received.  If the channel is not closed within 5 seconds,
      // print an error message and quit.
      if (!ch.closeFuture().await(5000)) {
        System.err.println("QOTM request timed out.");
      }
    } finally {
      group.shutdownGracefully();
    }
  }
  public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioDatagramChannel.class)
          .option(ChannelOption.SO_BROADCAST, true)
          .handler(new QuoteOfTheMomentServerHandler());

      b.bind(PORT).sync().channel().closeFuture().await();
    } finally {
      group.shutdownGracefully();
    }
  }
  public void run(final int port) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap boot = new Bootstrap();
      boot.group(group)
          .channel(NioDatagramChannel.class)
          .option(ChannelOption.SO_BROADCAST, true)
          .handler(
              new SimpleChannelInboundHandler<DatagramPacket>() {

                private final String[] DICTIONARY = {
                  "只要功夫深,铁棒磨成针。",
                  "旧时王谢堂前燕,飞入寻常百姓家。",
                  "洛阳亲友如相问,一片冰心在玉壶。",
                  "一寸光阴一寸金,寸金难买寸光阴。",
                  "老骥伏枥,志在千里。烈士暮年,壮心不已。"
                };

                @Override
                protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg)
                    throws Exception {
                  String req = msg.content().toString(CharsetUtil.UTF_8);
                  System.out.println("req=" + req);
                  if ("谚语字典查询?".equals(req)) {
                    ctx.writeAndFlush(
                        new DatagramPacket(
                            Unpooled.copiedBuffer("谚语查询结果: " + nextQuote(), CharsetUtil.UTF_8),
                            msg.sender()));
                  }
                }

                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                  cause.printStackTrace();
                  ctx.close();
                }

                private String nextQuote() {
                  return DICTIONARY[ThreadLocalRandom.current().nextInt(DICTIONARY.length)];
                }
              });
      boot.bind(new InetSocketAddress(port)).sync().channel().closeFuture().await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      group.shutdownGracefully();
    }
  }
  protected static Channel createAcceptorChannel(
      final ChannelType channelType,
      final InetSocketAddress localAddress,
      final MessageHandler handler) {
    final Bootstrap serverBootstrap = ServerUDPBootstrapFactory.createServerBootstrap(channelType);

    serverBootstrap
        .option(ChannelOption.SO_REUSEADDR, false)
        .handler(
            new ChannelInitializer<DatagramChannel>() {
              @Override
              protected void initChannel(final DatagramChannel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("messageDecoder", handler);
                // pipeline.addLast("handler", serverHandler);
              }
            });

    try {

      ChannelFuture channelFuture =
          serverBootstrap.bind(new InetSocketAddress(localAddress.getPort())).sync();

      // channelFuture.channel().closeFuture().awaitUninterruptibly();//.awaitUninterruptibly();
      channelFuture.awaitUninterruptibly();
      if (channelFuture.isSuccess()) {
        return channelFuture.channel();

      } else {

      }
    } catch (InterruptedException e) {

      // eventLoopGroup.shutdownGracefully();
      // System.exit(-1);
    }
    return null;
  }