io.netty.channel.socket.nio.NioDatagramChannel Java Examples

The following examples show how to use io.netty.channel.socket.nio.NioDatagramChannel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UdpReporterTest.java    From servicetalk with Apache License 2.0 7 votes vote down vote up
TestReceiver(SpanBytesDecoder decoder) throws Exception {
    channel = new Bootstrap()
            .group(group)
            .channel(NioDatagramChannel.class)
            .option(ChannelOption.RCVBUF_ALLOCATOR, DEFAULT_RECV_BUF_ALLOCATOR)
            .handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) {
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
                            byte[] b = new byte[msg.content().readableBytes()];
                            msg.content().readBytes(b);
                            decoder.decode(b, queue);
                        }
                    });
                }
            })
            .localAddress(localAddress(0))
            .bind().sync().channel();
}
 
Example #2
Source File: VoiceWebsocket.java    From kyoko with MIT License 6 votes vote down vote up
private CompletableFuture<Bootstrap> setupNetty(InetSocketAddress address, ChannelHandler handler) {
    var future = new CompletableFuture<Bootstrap>();

    var bootstrap = new Bootstrap()
            .group(vertx.nettyEventLoopGroup());

    if (Epoll.isAvailable()) {
        logger.info("epoll support is available, using it for UDP connections.");
        bootstrap.channel(EpollDatagramChannel.class);
    } else {
        logger.info("epoll unavailable, falling back to NIO.");
        bootstrap.channel(NioDatagramChannel.class);
    }

    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.IP_TOS, 0x10 | 0x08); // IPTOS_LOWDELAY | IPTOS_THROUGHPUT
    bootstrap.handler(handler).connect(address).addListener(res -> {
        if (res.isSuccess()) {
            future.complete(bootstrap);
        } else {
            future.completeExceptionally(res.cause());
        }
    });

    return future;
}
 
Example #3
Source File: UDPServerSocket.java    From Nemisys with GNU General Public License v3.0 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example #4
Source File: UDPServerSocket.java    From BukkitPE with GNU General Public License v3.0 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (InterruptedException e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("-------------------------------------------------");
        this.logger.critical("There may be another server running on that port!");
        this.logger.critical("--------------------------------------------------");
        System.exit(1);
    }
}
 
Example #5
Source File: UdpServerChannel.java    From UdpServerSocketChannel with GNU Lesser General Public License v3.0 6 votes vote down vote up
public UdpServerChannel(int ioThreads) {
	if (ioThreads < 1) {
		throw new IllegalArgumentException("IO threads cound can't be less than 1");
	}
	boolean epollAvailabe = Epoll.isAvailable();
	if (!epollAvailabe) {
		ioThreads = 1;
	}
	group = epollAvailabe ? new EpollEventLoopGroup(ioThreads) : new NioEventLoopGroup(ioThreads);
	Class<? extends DatagramChannel> channel = epollAvailabe ? EpollDatagramChannel.class : NioDatagramChannel.class;
	ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {
		final ReadRouteChannelHandler ioReadRoute = new ReadRouteChannelHandler();
		@Override
		protected void initChannel(Channel ioChannel) throws Exception {
			ioChannel.pipeline().addLast(ioReadRoute);
		}
	};
	while (ioThreads-- > 0) {
		Bootstrap ioBootstrap = new Bootstrap().group(group).channel(channel).handler(initializer);
		if (epollAvailabe) {
			ioBootstrap.option(UnixChannelOption.SO_REUSEPORT, true);
		}
		ioBootstraps.add(ioBootstrap);
	}
}
 
Example #6
Source File: Server.java    From heroic with Apache License 2.0 6 votes vote down vote up
static AsyncFuture<Server> setup(
    final AsyncFramework async, final CollectdChannelHandler handler, final InetAddress host,
    final int port
) {
    final EventLoopGroup group = new NioEventLoopGroup();
    final Bootstrap b = new Bootstrap();

    b
        .group(group)
        .channel(NioDatagramChannel.class)
        .option(ChannelOption.SO_BROADCAST, true)
        .handler(handler);

    final ResolvableFuture<Server> future = async.future();

    b.bind(host, port).addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            future.resolve(new Server(async, f.channel()));
        } else {
            future.fail(
                f.cause() != null ? f.cause() : new RuntimeException("Failed to bind"));
        }
    });

    return future;
}
 
Example #7
Source File: NettyUnicastService.java    From atomix with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Void> bootstrap() {
  Bootstrap serverBootstrap = new Bootstrap()
      .group(group)
      .channel(NioDatagramChannel.class)
      .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
        @Override
        protected void channelRead0(ChannelHandlerContext context, DatagramPacket packet) throws Exception {
          byte[] payload = new byte[packet.content().readInt()];
          packet.content().readBytes(payload);
          Message message = SERIALIZER.decode(payload);
          Map<BiConsumer<Address, byte[]>, Executor> listeners = NettyUnicastService.this.listeners.get(message.subject());
          if (listeners != null) {
            listeners.forEach((consumer, executor) ->
                executor.execute(() -> consumer.accept(message.source(), message.payload())));
          }
        }
      })
      .option(ChannelOption.RCVBUF_ALLOCATOR, new DefaultMaxBytesRecvByteBufAllocator())
      .option(ChannelOption.SO_BROADCAST, true)
      .option(ChannelOption.SO_REUSEADDR, true);

  return bind(serverBootstrap);
}
 
Example #8
Source File: NettyBroadcastService.java    From atomix with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Void> bootstrapServer() {
  Bootstrap serverBootstrap = new Bootstrap()
      .group(group)
      .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
      .handler(new SimpleChannelInboundHandler<Object>() {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
          // Nothing will be sent.
        }
      })
      .option(ChannelOption.IP_MULTICAST_IF, iface)
      .option(ChannelOption.SO_REUSEADDR, true);

  CompletableFuture<Void> future = new CompletableFuture<>();
  serverBootstrap.bind(localAddress).addListener((ChannelFutureListener) f -> {
    if (f.isSuccess()) {
      serverChannel = f.channel();
      future.complete(null);
    } else {
      future.completeExceptionally(f.cause());
    }
  });
  return future;
}
 
Example #9
Source File: UDPServerSocket.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
            bootstrap = new Bootstrap()
                    .channel(EPOLL ? EpollDatagramChannel.class : NioDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(this)
                    .group(EPOLL ? new EpollEventLoopGroup() : new NioEventLoopGroup());
            this.logger.info("Epoll Status is " + EPOLL);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example #10
Source File: UDPServerSocket.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical(FastAppender.get(interfaz, ":", port, " 上でサーバーを開けませんでした。"));
        this.logger.critical("同じポートで複数のサーバーを一度に開いていませんか?");
        System.exit(1);
    }
}
 
Example #11
Source File: DnsNameResolverTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static DnsNameResolverBuilder newResolver(boolean decodeToUnicode,
                                                  DnsServerAddressStreamProvider dnsServerAddressStreamProvider) {
    DnsNameResolverBuilder builder = new DnsNameResolverBuilder(group.next())
            .dnsQueryLifecycleObserverFactory(new TestRecursiveCacheDnsQueryLifecycleObserverFactory())
            .channelType(NioDatagramChannel.class)
            .maxQueriesPerResolve(1)
            .decodeIdn(decodeToUnicode)
            .optResourceEnabled(false)
            .ndots(1);

    if (dnsServerAddressStreamProvider == null) {
        builder.nameServerProvider(new SingletonDnsServerAddressStreamProvider(dnsServer.localAddress()));
    } else {
        builder.nameServerProvider(new MultiDnsServerAddressStreamProvider(dnsServerAddressStreamProvider,
                new SingletonDnsServerAddressStreamProvider(dnsServer.localAddress())));
    }

    return builder;
}
 
Example #12
Source File: SocketTestPermutation.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public List<BootstrapFactory<Bootstrap>> datagramSocket() {
    return Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channel(NioDatagramChannel.class);
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(oioWorkerGroup).channel(OioDatagramChannel.class)
                            .option(ChannelOption.SO_TIMEOUT, OIO_SO_TIMEOUT);
                }
            }
    );
}
 
Example #13
Source File: UAS.java    From sipstack with MIT License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final UAS uas = new UAS();
    final EventLoopGroup udpGroup = new NioEventLoopGroup();

    final Bootstrap b = new Bootstrap();
    b.group(udpGroup)
    .channel(NioDatagramChannel.class)
    .handler(new ChannelInitializer<DatagramChannel>() {
        @Override
        protected void initChannel(final DatagramChannel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new SipMessageDatagramDecoder());
            pipeline.addLast("encoder", new SipMessageEncoder());
            pipeline.addLast("handler", uas);
        }
    });

    final InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 5060);
    b.bind(socketAddress).sync().channel().closeFuture().await();
}
 
Example #14
Source File: DhcpServer.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void start() throws IOException, InterruptedException {
    super.start();

    ThreadFactory factory = new DefaultThreadFactory("dhcp-server");
    EventLoopGroup group = new NioEventLoopGroup(0, factory);

    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioDatagramChannel.class);
    b.option(ChannelOption.SO_BROADCAST, true);
    b.handler(new DhcpHandler(service, this));
    channel = b.bind(port).sync().channel();
}
 
Example #15
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example #16
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example #17
Source File: DhcpServer.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void start() throws IOException, InterruptedException {
    super.start();

    ThreadFactory factory = new DefaultThreadFactory("dhcp-server");
    EventLoopGroup group = new NioEventLoopGroup(0, factory);

    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioDatagramChannel.class);
    b.option(ChannelOption.SO_BROADCAST, true);
    b.handler(new DhcpHandler(service, this));
    channel = b.bind(port).sync().channel();
}
 
Example #18
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example #19
Source File: ProtocolServersImpl.java    From ffwd with Apache License 2.0 5 votes vote down vote up
private AsyncFuture<ProtocolConnection> bindUDP(
    final Logger log, final Protocol protocol, ProtocolServer server, RetryPolicy policy
) {
    final Bootstrap b = new Bootstrap();

    b.group(worker);
    b.channel(NioDatagramChannel.class);
    b.handler(server.initializer());

    if (protocol.getReceiveBufferSize() != null) {
        b.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    final String host = protocol.getAddress().getHostString();
    final int port = protocol.getAddress().getPort();

    final RetryingProtocolConnection connection =
        new RetryingProtocolConnection(async, timer, log, policy, new ProtocolChannelSetup() {
            @Override
            public ChannelFuture setup() {
                return b.bind(host, port);
            }

            @Override
            public String toString() {
                return String.format("bind udp://%s:%d", host, port);
            }
        });

    return connection.getInitialFuture();
}
 
Example #20
Source File: Main.java    From riiablo with Apache License 2.0 5 votes vote down vote up
@Override
  public void create() {
    Gdx.app.setLogLevel(Application.LOG_DEBUG);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
//    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap()
          .group(bossGroup)
          .channel(NioDatagramChannel.class)
          .option(ChannelOption.SO_BROADCAST, true)
          .handler(new ChannelInitializer<DatagramChannel>() {
            @Override
            protected void initChannel(DatagramChannel ch) {
              ch.pipeline()
                  .addLast(new ServerHandler())
                  ;
            }
          })
          ;

      ChannelFuture f = b.bind(PORT).sync();
      f.channel().closeFuture().sync();
    } catch (Throwable t) {
      Gdx.app.error(TAG, t.getMessage(), t);
    } finally {
//      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();
    }
  }
 
Example #21
Source File: Client.java    From riiablo with Apache License 2.0 5 votes vote down vote up
@Override
public void create() {
  Gdx.app.setLogLevel(Application.LOG_DEBUG);

  EventLoopGroup group = new NioEventLoopGroup();
  try {
    Bootstrap b = new Bootstrap()
        .group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<DatagramChannel>() {
          @Override
          protected void initChannel(DatagramChannel ch) {
            final ClientHandler client = new ClientHandler();
            ch.pipeline()
                .addLast(client)
                .addLast(new ChannelInboundHandlerAdapter() {
                  @Override
                  public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    client.init(ctx);
                    client.init(ctx);
                    client.init(ctx);
                    ctx.pipeline().remove(this);
                  }
                })
                ;
          }
        });

    ChannelFuture f = b.connect("localhost", Main.PORT);
    f.channel().closeFuture().sync();
  } catch (Throwable t) {
    Gdx.app.error(TAG, t.getMessage(), t);
  } finally {
    group.shutdownGracefully();
  }
}
 
Example #22
Source File: TestServer.java    From riiablo with Apache License 2.0 5 votes vote down vote up
@Override
public void create() {
  Gdx.app.setLogLevel(Application.LOG_DEBUG);

  group = new NioEventLoopGroup();
  try {
    Bootstrap b = new Bootstrap()
        .group(group)
        .channel(NioDatagramChannel.class)
        .option(ChannelOption.SO_BROADCAST, true)
        .handler(new ChannelInitializer<DatagramChannel>() {
          @Override
          protected void initChannel(DatagramChannel ch) {
            ReliableEndpoint endpoint = new ReliableEndpoint(ch, TestServer.this);
            TestServer.this.endpoint = endpoint;
            ch.pipeline()
                .addLast(new EndpointedChannelHandler<>(DatagramPacket.class, endpoint))
                ;
          }
        })
        ;

    ChannelFuture f = b.bind(PORT).sync();
  } catch (Throwable t) {
    Gdx.app.error(TAG, t.getMessage(), t);
    Gdx.app.exit();
  }
}
 
Example #23
Source File: TestClient.java    From riiablo with Apache License 2.0 5 votes vote down vote up
@Override
public void create() {
  Gdx.app.setLogLevel(Application.LOG_DEBUG);

  group = new NioEventLoopGroup();
  try {
    Bootstrap b = new Bootstrap()
        .group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<DatagramChannel>() {
          @Override
          protected void initChannel(DatagramChannel ch) {
            UnicastEndpoint<DatagramPacket> endpoint = new ReliableEndpoint(ch, TestClient.this);
            TestClient.this.endpoint = endpoint;
            ch.pipeline()
                .addLast(new EndpointedChannelHandler<>(DatagramPacket.class, endpoint))
                ;
          }
        });

    ChannelFuture f = b.connect("localhost", TestServer.PORT).sync();
    sendPacket();
  } catch (Throwable t) {
    Gdx.app.error(TAG, t.getMessage(), t);
    Gdx.app.exit();
  }
}
 
Example #24
Source File: EpollSocketTestPermutation.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public List<TestsuitePermutation.BootstrapComboFactory<Bootstrap, Bootstrap>> datagram() {
    // Make the list of Bootstrap factories.
    List<BootstrapFactory<Bootstrap>> bfs = Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory<Channel>() {
                        @Override
                        public Channel newChannel() {
                            return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                        }

                        @Override
                        public String toString() {
                            return NioDatagramChannel.class.getSimpleName() + ".class";
                        }
                    });
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollDatagramChannel.class);
                }
            }
    );
    return combo(bfs, bfs);
}
 
Example #25
Source File: NioDatagramChannelTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Test try to reproduce issue #1335
 */
@Test
public void testBindMultiple() throws Exception {
    DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        for (int i = 0; i < 100; i++) {
            Bootstrap udpBootstrap = new Bootstrap();
            udpBootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            // Discard
                            ReferenceCountUtil.release(msg);
                        }
                    });
            DatagramChannel datagramChannel = (DatagramChannel) udpBootstrap
                    .bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
            channelGroup.add(datagramChannel);
        }
        Assert.assertEquals(100, channelGroup.size());
    } finally {
        channelGroup.close().sync();
        group.shutdownGracefully().sync();
    }
}
 
Example #26
Source File: SocketTestPermutation.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public List<BootstrapComboFactory<Bootstrap, Bootstrap>> datagram() {
    // Make the list of Bootstrap factories.
    List<BootstrapFactory<Bootstrap>> bfs = Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channelFactory(new ChannelFactory<Channel>() {
                        @Override
                        public Channel newChannel() {
                            return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                        }

                        @Override
                        public String toString() {
                            return NioDatagramChannel.class.getSimpleName() + ".class";
                        }
                    });
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(oioWorkerGroup).channel(OioDatagramChannel.class);
                }
            }
    );

    // Populare the combinations.
    return combo(bfs, bfs);
}
 
Example #27
Source File: QuoteOfTheMomentClient.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
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 QuoteOfTheMomentClientHandler());

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

            // Broadcast the QOTM request to port 8080.
            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                    new InetSocketAddress("255.255.255.255", PORT))).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();
        }
    }
 
Example #28
Source File: QuoteOfTheMomentServer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #29
Source File: UdpServer.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {

    if ((port_ < 0) || (port_ > 65535)) {
        logger.error("Error running " + serverType_.toLowerCase() + " UDP server. Bad input arguments.");
        initializeSuccess = false;
        return;
    }

    try {
        group_ = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();

        if (serverType_.equals(SERVER_TYPE_STATSD)) {
            b.group(group_).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new UdpServerHandler_Statsd());
        }
        else if (serverType_.equals(SERVER_TYPE_GRAPHITE_AGGREGATOR)) {
            b.group(group_).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new UdpServerHandler_GraphiteAggregator());
        }
        else if (serverType_.equals(SERVER_TYPE_GRAPHITE_PASSTHROUGH)) {
            b.group(group_).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new UdpServerHandler_GraphitePassthrough());
        }
        
        b.bind(port_).sync().channel().closeFuture().await();
    }
    catch (Exception e) {
        initializeSuccess = false;
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
    finally {
        shutdownServer();
    }
}
 
Example #30
Source File: QuoteOfTheMomentServer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
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();
    }
}