Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener.

Prototype

GenericFutureListener

Source Link

Usage

From source file:me.melchor9000.net.TCPSocket.java

License:Open Source License

private void channelCreated() {
    socket = (SocketChannel) channel;
    if (socket != null) {
        socket.closeFuture()/*from   ww  w .  j av a 2 s.  c om*/
                .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
                    @Override
                    public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                            throws Exception {
                        isClosed = true;
                    }
                });
    }
}

From source file:me.netty.http.HttpServer.java

License:Apache License

public void start() throws Exception {
    //?/*from   w  w w  . j  ava 2 s.com*/
    serverContext.initContext();

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the http2Orhttp.

    //CPU??workwork?
    // ?????
    int threads = Runtime.getRuntime().availableProcessors() * 2;

    EventLoopGroup bossGroup = new NioEventLoopGroup(threads);
    EventLoopGroup workerGroup = new NioEventLoopGroup(threads);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new Http2ServerInitializer(sslCtx));

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

        logger.info("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "http")
                + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync().addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                logger.info("service has shutdown");
            }
        });
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

From source file:net.epsilony.utils.codec.modbus.ModbusClientMaster.java

License:Open Source License

public CompletableFuture<ModbusResponse> request(ModbusRequest req) {
    final CompletableFuture<ModbusResponse> result = new CompletableFuture<>();

    result.whenComplete((res, ex) -> {
        if (transectionIdDispatcher != null) {
            int transectionId = req.getTransectionId();
            if (transectionId >= 0) {
                transectionIdDispatcher.repay(transectionId);
            }//from  w  w  w.j  av a 2s  .  com
        }
    });

    lock.lock();
    try {
        if (connectFuture == null) {
            connectFuture = genConnectFuture();
            connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    lock.lock();
                    try {
                        if (future.isSuccess()) {
                            channel = connectFuture.channel();
                            channel.closeFuture()
                                    .addListener(new GenericFutureListener<Future<? super Void>>() {

                                        @Override
                                        public void operationComplete(Future<? super Void> future)
                                                throws Exception {
                                            lock.lock();
                                            try {
                                                connectFuture = null;
                                                initializer.clearExceptionally(
                                                        new ConnectException("connection is closed!"));
                                                transectionIdDispatcher.reset();
                                            } finally {
                                                lock.unlock();
                                            }
                                        }
                                    });
                        } else {
                            connectFuture = null;
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }

        connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                ChannelFuture channelFuture = (ChannelFuture) future;
                if (future.isSuccess()) {
                    if (null != transectionIdDispatcher) {
                        int transectionId = transectionIdDispatcher.borrow();
                        req.setTransectionId(transectionId);
                        if (transectionId < 0) {
                            result.completeExceptionally(new TransectionDispatcherEmptyException());
                            return;
                        }
                    }

                    try {
                        initializer.register(result, req);
                    } catch (Throwable ex) {
                        result.completeExceptionally(ex);
                        return;
                    }

                    ChannelFuture writeFuture = channelFuture.channel().writeAndFlush(req);
                    writeFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                        @Override
                        public void operationComplete(Future<? super Void> future) throws Exception {
                            if (!future.isSuccess()) {
                                if (future.isCancelled()) {
                                    initializer.removeExceptionally(req.getTransectionId(),
                                            new ConnectException("connection is canncelled"));
                                } else {
                                    initializer.removeExceptionally(req.getTransectionId(), future.cause());
                                }
                            }
                        }
                    });
                } else if (future.isCancelled()) {
                    result.completeExceptionally(new ConnectException("connection is canncelled"));
                } else {
                    result.completeExceptionally(future.cause());
                }
            }

        });
    } finally {
        lock.unlock();
    }

    return result;

}

From source file:net.tomp2p.connection.ChannelCreator.java

License:Apache License

/**
 * When a channel is closed, the semaphore is released an other channel can
 * be created. Also the lock for the channel creating is being released.
 * This means that the channelCreator can be shutdown.
 * //from w  ww.  ja v a  2s  .c  om
 * @param channelFuture
 *            The channel future
 * @param semaphore
 *            The semaphore to decrease
 * @param futureResponse
 *            The future response
 * 
 * @return The same future that was passed as an argument
 */
private ChannelFuture setupCloseListener(final ChannelFuture channelFuture, final Semaphore semaphore,
        final FutureResponse futureResponse) {
    channelFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            // it is important that the release of the semaphore and the set
            // of the future happen sequentially. If this is run in this
            // thread it will be a netty thread, and this is not what the
            // user may have wanted. The future response should be executed
            // in the thread of the handler.
            Runnable runner = new Runnable() {
                @Override
                public void run() {
                    semaphore.release();

                    Message request = futureResponse.request();
                    if (request != null && futureResponse.responseMessage() == null
                            && request.recipient().isSlow() && request.command() != Commands.PING.getNr()
                            && request.command() != Commands.NEIGHBOR.getNr()) {
                        // If the request goes to a slow peer, the channel
                        // can be closed until the response arrives
                        LOG.debug("Ignoring channel close event because recipient is slow peer");
                    } else {
                        futureResponse.responseNow();
                    }
                }
            };
            if (handlerExecutor == null) {
                runner.run();
            } else {
                handlerExecutor.submit(runner);
            }
        }
    });
    return channelFuture;
}

From source file:net.tomp2p.connection.ChannelCreator.java

License:Apache License

/**
 * Setup the close listener for a channel that was already created
 * /*from   w  w w.  ja va 2  s  .  c o m*/
 * @param channelFuture
 *            The channel future
 * @param futureResponse
 *            The future response
 * @return The same future that was passed as an argument
 */
public ChannelFuture setupCloseListener(final ChannelFuture channelFuture,
        final FutureResponse futureResponse) {
    channelFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            futureResponse.responseNow();
        }
    });
    return channelFuture;
}

From source file:net.tomp2p.connection.ChannelCreator.java

License:Apache License

/**
 * Shutdown this channel creator. This means that no TCP or UDP connection
 * can be established.// ww w  . j  a  va  2s . c o  m
 * 
 * @return The shutdown future.
 */
public FutureDone<Void> shutdown() {
    // set shutdown flag for UDP and TCP, if we acquire a write lock, all
    // read locks are blocked as well
    writeUDP.lock();
    writeTCP.lock();
    try {
        if (shutdownTCP || shutdownUDP) {
            shutdownFuture().failed("already shutting down");
            return shutdownFuture();
        }
        shutdownUDP = true;
        shutdownTCP = true;
    } finally {
        writeTCP.unlock();
        writeUDP.unlock();
    }

    recipients.close().addListener(new GenericFutureListener<ChannelGroupFuture>() {
        @Override
        public void operationComplete(final ChannelGroupFuture future) throws Exception {
            // we can block here as we block in GlobalEventExecutor.INSTANCE
            semaphoreUPD.acquireUninterruptibly(maxPermitsUDP);
            semaphoreTCP.acquireUninterruptibly(maxPermitsTCP);
            shutdownFuture().done();
        }
    });

    return shutdownFuture();
}

From source file:net.tomp2p.connection.ChannelServer.java

License:Apache License

/**
 * Shuts down the server.//from  w  ww .  j ava2 s . c  o m
 * 
 * @return The future when the shutdown is complete. This includes the
 *         worker and boss event loop
 */
public FutureDone<Void> shutdown() {
    synchronized (this) {
        shutdown = true;
    }
    discoverNetworks.stop();
    final int maxListeners = channelsTCP.size() + channelsUDP.size();
    if (maxListeners == 0) {
        shutdownFuture().done();
    }
    // we have two things to shut down: UDP and TCP
    final AtomicInteger listenerCounter = new AtomicInteger(0);
    LOG.debug("shutdown servers");
    synchronized (channelsUDP) {
        for (Channel channelUDP : channelsUDP.values()) {
            channelUDP.close().addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(final ChannelFuture future) throws Exception {
                    LOG.debug("shutdown TCP server");
                    if (listenerCounter.incrementAndGet() == maxListeners) {
                        futureServerDone.done();
                    }
                }
            });
        }
    }
    synchronized (channelsTCP) {
        for (Channel channelTCP : channelsTCP.values()) {
            channelTCP.close().addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(final ChannelFuture future) throws Exception {
                    LOG.debug("shutdown TCP channels");
                    if (listenerCounter.incrementAndGet() == maxListeners) {
                        futureServerDone.done();
                    }
                }
            });
        }
    }
    return shutdownFuture();
}

From source file:net.tomp2p.connection.Dispatcher.java

License:Apache License

/**
 * Respond within a session. Keep the connection open if we are asked to do so. Connection is only kept alive for
 * TCP data.//from  w w w .  jav  a2s.c o m
 * 
 * @param ctx
 *            The channel context
 * @param response
 *            The response to send
 */
private FutureDone<Void> response(final ChannelHandlerContext ctx, final Message response) {
    final FutureDone<Void> futureDone = new FutureDone<Void>();
    if (ctx.channel() instanceof DatagramChannel) {
        // check if channel is still open. If its not, then do not send
        // anything because
        // this will cause an exception that will be logged.
        if (!ctx.channel().isOpen()) {
            LOG.debug("channel UDP is not open, do not reply {}", response);
            return futureDone.failed("channel UDP is not open, do not reply");
        }
        LOG.debug("reply UDP message {}", response);
    } else {
        // check if channel is still open. If its not, then do not send
        // anything because
        // this will cause an exception that will be logged.
        if (!ctx.channel().isActive()) {
            LOG.debug("channel TCP is not open, do not reply {}", response);
            return futureDone.failed("channel TCP is not open, do not reply");
        }
        LOG.debug("reply TCP message {} to {}", response, ctx.channel().remoteAddress());
    }

    ctx.channel().writeAndFlush(response).addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            //TODO: we could check if we were successful at this stage
            futureDone.done();
        }
    });
    return futureDone;
}

From source file:net.tomp2p.connection.PeerCreator.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private void shutdownNetty() {
    workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS).addListener(new GenericFutureListener() {
        @Override//w w  w  .  j a va 2  s. c  o m
        public void operationComplete(final Future future) throws Exception {
            LOG.debug("shutdown done in client / workerGroup...");
            bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS).addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(final Future future) throws Exception {
                    LOG.debug("shutdown done in client / bossGroup...");
                    futureServerDone.done();
                }
            });
        }
    });
}

From source file:net.tomp2p.connection.Sender.java

License:Apache License

/**
 * After connecting, we check if the connect was successful.
 * //  ww w.  j  av a  2s  . c  o  m
 * @param futureResponse
 *            The future to set the response
 * @param message
 *            The message to send
 * @param channelFuture
 *            the future of the connect
 * @param fireAndForget
 *            True, if we don't expect a message
 */
public void afterConnect(final FutureResponse futureResponse, final Message message,
        final ChannelFuture channelFuture, final boolean fireAndForget) {
    if (channelFuture == null) {
        futureResponse.failed("could not create a " + (message.isUdp() ? "UDP" : "TCP") + " channel");
        return;
    }
    LOG.debug("about to connect to {} with channel {}, ff={}", message.recipient(), channelFuture.channel(),
            fireAndForget);
    final Cancel connectCancel = createCancel(channelFuture);
    futureResponse.addCancel(connectCancel);
    channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            futureResponse.removeCancel(connectCancel);
            if (future.isSuccess()) {
                final ChannelFuture writeFuture = future.channel().writeAndFlush(message);
                afterSend(writeFuture, futureResponse, fireAndForget);
            } else {
                LOG.debug("Channel creation failed", future.cause());
                futureResponse.failed("Channel creation failed " + future.channel() + "/" + future.cause());
                // may have been closed by the other side,
                // or it may have been canceled from this side
                if (!(future.cause() instanceof CancellationException)
                        && !(future.cause() instanceof ClosedChannelException)
                        && !(future.cause() instanceof ConnectException)) {
                    LOG.warn("Channel creation failed to {} for {}", future.channel(), message);
                }
            }
        }
    });
}