Example usage for io.netty.channel.socket DatagramChannel closeFuture

List of usage examples for io.netty.channel.socket DatagramChannel closeFuture

Introduction

In this page you can find the example usage for io.netty.channel.socket DatagramChannel closeFuture.

Prototype

ChannelFuture closeFuture();

Source Link

Document

Returns the ChannelFuture which will be notified when this channel is closed.

Usage

From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java

License:Apache License

/**
 * Creates a new DNS-based name resolver that communicates with the specified list of DNS servers.
 *
 * @param eventLoop the {@link EventLoop} which will perform the communication with the DNS servers
 * @param channelFactory the {@link ChannelFactory} that will create a {@link DatagramChannel}
 * @param nameServerAddresses the addresses of the DNS server. For each DNS query, a new stream is created from
 *                            this to determine which DNS server should be contacted for the next retry in case
 *                            of failure.
 * @param resolveCache the DNS resolved entries cache
 * @param queryTimeoutMillis timeout of each DNS query in millis
 * @param resolvedAddressTypes list of the protocol families
 * @param recursionDesired if recursion desired flag must be set
 * @param maxQueriesPerResolve the maximum allowed number of DNS queries for a given name resolution
 * @param traceEnabled if trace is enabled
 * @param maxPayloadSize the capacity of the datagram packet buffer
 * @param optResourceEnabled if automatic inclusion of a optional records is enabled
 * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to check for local aliases
 * @param searchDomains TODO/*from  ww  w  .  j  av  a  2  s  . c o  m*/
 * @param ndots TODO
 */
public DnsNameResolver(EventLoop eventLoop, ChannelFactory<? extends DatagramChannel> channelFactory,
        DnsServerAddresses nameServerAddresses, DnsCache resolveCache, long queryTimeoutMillis,
        InternetProtocolFamily[] resolvedAddressTypes, boolean recursionDesired, int maxQueriesPerResolve,
        boolean traceEnabled, int maxPayloadSize, boolean optResourceEnabled,
        HostsFileEntriesResolver hostsFileEntriesResolver, List<String> searchDomains, int ndots) {

    super(eventLoop);
    checkNotNull(channelFactory, "channelFactory");
    this.nameServerAddresses = checkNotNull(nameServerAddresses, "nameServerAddresses");
    this.queryTimeoutMillis = checkPositive(queryTimeoutMillis, "queryTimeoutMillis");
    this.resolvedAddressTypes = checkNonEmpty(resolvedAddressTypes, "resolvedAddressTypes");
    this.recursionDesired = recursionDesired;
    this.maxQueriesPerResolve = checkPositive(maxQueriesPerResolve, "maxQueriesPerResolve");
    this.traceEnabled = traceEnabled;
    this.maxPayloadSize = checkPositive(maxPayloadSize, "maxPayloadSize");
    this.optResourceEnabled = optResourceEnabled;
    this.hostsFileEntriesResolver = checkNotNull(hostsFileEntriesResolver, "hostsFileEntriesResolver");
    this.resolveCache = resolveCache;
    this.searchDomains = checkNotNull(searchDomains, "searchDomains");
    this.ndots = checkPositive(ndots, "ndots");

    Bootstrap b = new Bootstrap();
    b.group(executor());
    b.channelFactory(channelFactory);
    b.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
    final DnsResponseHandler responseHandler = new DnsResponseHandler(executor().<Channel>newPromise());
    b.handler(new ChannelInitializer<DatagramChannel>() {
        @Override
        protected void initChannel(DatagramChannel ch) throws Exception {
            ch.pipeline().addLast(DECODER, ENCODER, responseHandler);
        }
    });

    channelFuture = responseHandler.channelActivePromise;
    ch = (DatagramChannel) b.register().channel();
    ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(maxPayloadSize));

    ch.closeFuture().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            resolveCache.clear();
        }
    });
}

From source file:org.aotorrent.common.connection.UDPTrackerConnection.java

License:Apache License

@Override
protected void obtainPeers() {
    try {/*ww  w.  java2  s  .  c  o m*/
        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();

        b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<DatagramChannel>() {
            @Override
            protected void initChannel(DatagramChannel ch) throws Exception {
                final ChannelPipeline p = ch.pipeline();
                p.addLast(new TrackerConnectionHandler());
            }
        });

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

        transactionId = RANDOM.nextInt();
        LOGGER.debug("Sending connect request to " + address);
        ch.writeAndFlush(new DatagramPacket(new UDPConnectRequest(transactionId).toTransmit(), address));

        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("Tracker connection interrupted");
    }

}

From source file:org.hawkular.metrics.clients.ptrans.PTrans.java

License:Apache License

/**
 * Starts this PTrans instance. the calling thread will be blocked until another thread calls {@link #stop()}.
 *///  w w w  .  j  ava2s  .c o  m
public void start() {
    LOG.info("Starting ptrans...");

    Set<Service> services = configuration.getServices();
    List<ChannelFuture> closeFutures = new ArrayList<>(services.size());

    if (services.contains(Service.TCP)) {
        ServerBootstrap serverBootstrap = new ServerBootstrap().group(group, workerGroup)
                .channel(NioServerSocketChannel.class).localAddress(configuration.getTcpPort())
                .childHandler(new TcpChannelInitializer(configuration, forwardingHandler));
        ChannelFuture tcpBindFuture = serverBootstrap.bind().syncUninterruptibly();
        LOG.info("Server listening on TCP {}", tcpBindFuture.channel().localAddress());
        closeFutures.add(tcpBindFuture.channel().closeFuture());
    }

    if (services.contains(Service.UDP)) {
        Bootstrap udpBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class)
                .localAddress(configuration.getUdpPort()).handler(new UdpChannelInitializer(forwardingHandler));
        ChannelFuture udpBindFuture = udpBootstrap.bind().syncUninterruptibly();
        LOG.info("Syslogd listening on UDP {}", udpBindFuture.channel().localAddress());
        closeFutures.add(udpBindFuture.channel().closeFuture());
    }

    if (services.contains(Service.GANGLIA)) {
        NetworkInterface mcIf;
        try {
            String multicastIfOverride = configuration.getMulticastIfOverride();
            if (multicastIfOverride == null) {
                Inet4Address hostAddr = (Inet4Address) InetAddress.getLocalHost();
                mcIf = NetworkInterface.getByInetAddress(hostAddr);
            } else {
                mcIf = NetworkInterface.getByName(multicastIfOverride);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        InetSocketAddress gangliaSocket = new InetSocketAddress(configuration.getGangliaGroup(),
                configuration.getGangliaPort());
        Bootstrap gangliaBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.IP_MULTICAST_IF, mcIf)
                .localAddress(gangliaSocket)
                .handler(new GangliaChannelInitializer(configuration, forwardingHandler));
        LOG.trace("Ganglia bootstrap is {}", gangliaBootstrap);
        ChannelFuture gangliaBindFuture = gangliaBootstrap.bind().syncUninterruptibly();
        LOG.info("Ganglia listening on UDP {}", gangliaBindFuture.channel().localAddress());
        DatagramChannel gangliaChannel = (DatagramChannel) gangliaBindFuture.channel();
        gangliaChannel.joinGroup(gangliaSocket, mcIf);
        LOG.trace("Joined the Ganglia group");
        closeFutures.add(gangliaChannel.closeFuture());
    }

    if (services.contains(Service.STATSD)) {
        Bootstrap statsdBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class)
                .localAddress(configuration.getStatsDport())
                .handler(new StatsdChannelInitializer(configuration, forwardingHandler));
        ChannelFuture statsdBindFuture = statsdBootstrap.bind().syncUninterruptibly();
        LOG.info("Statsd listening on UDP {}", statsdBindFuture.channel().localAddress());
        closeFutures.add(statsdBindFuture.channel().closeFuture());
    }

    if (services.contains(Service.COLLECTD)) {
        Bootstrap collectdBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class)
                .localAddress(configuration.getCollectdPort())
                .handler(new CollectdChannelInitializer(configuration, forwardingHandler));
        ChannelFuture collectdBindFuture = collectdBootstrap.bind().syncUninterruptibly();
        LOG.info("Collectd listening on UDP {}", collectdBindFuture.channel().localAddress());
        closeFutures.add(collectdBindFuture.channel().closeFuture());
    }

    LOG.info("ptrans started");

    closeFutures.forEach(ChannelFuture::syncUninterruptibly);
}