Example usage for io.netty.channel ChannelFuture addListener

List of usage examples for io.netty.channel ChannelFuture addListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture addListener.

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:net.sourceforge.entrainer.socket.WebSocketHandler.java

License:Open Source License

private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//from  www . j  a  v a 2  s . c  o  m
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:net.telnet.TelnetServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) {
    // Generate and write a response.
    String response;//from w ww  .  j a  v  a2 s. c om
    boolean close = false;
    if (request.isEmpty()) {
        response = "Please type something.\r\n";
    } else if ("bye".equals(request.toLowerCase())) {
        response = "Have a good day!\r\n";
        close = true;
    } else {
        response = "Did you say '" + request + "'?\r\n";
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    ChannelFuture future = ctx.write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'bye'.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

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

License:Apache License

/**
 * After connecting, we check if the connect was successful.
 * /*ww w .ja v a  2  s  .co 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);
                }
            }
        }
    });
}

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

License:Apache License

/**
 * After sending, we check if the write was successful or if it was a fire
 * and forget./*from w  ww.j  ava  2 s  .co  m*/
 * 
 * @param writeFuture
 *            The future of the write operation. Can be UDP or TCP
 * @param futureResponse
 *            The future to set the response
 * @param fireAndForget
 *            True, if we don't expect a message
 */
private void afterSend(final ChannelFuture writeFuture, final FutureResponse futureResponse,
        final boolean fireAndForget) {
    final Cancel writeCancel = createCancel(writeFuture);
    writeFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            futureResponse.removeCancel(writeCancel);
            if (!future.isSuccess()) {
                futureResponse.failedLater(future.cause());
                reportFailed(futureResponse, future.channel().close());
                LOG.warn("Failed to write channel the request {} {}", futureResponse.request(), future.cause());
            }
            if (fireAndForget) {
                futureResponse.responseLater(null);
                LOG.debug("fire and forget, close channel now {}, {}", futureResponse.request(),
                        future.channel());
                reportMessage(futureResponse, future.channel().close());
            }
        }
    });

}

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

License:Apache License

/**
 * Report a failure after the channel was closed.
 * /*from   w  w w.  j a  va2s  .  c  o m*/
 * @param futureResponse
 *            The future to set the response
 * @param close
 *            The close future
 */
private void reportFailed(final FutureResponse futureResponse, final ChannelFuture close) {
    close.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture arg0) throws Exception {
            futureResponse.responseNow();
        }
    });
}

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

License:Apache License

/**
 * Report a successful response after the channel was closed.
 * /* w w w  .j a v  a2  s.  com*/
 * @param futureResponse
 *            The future to set the response
 * @param close
 *            The close future
 */
private void reportMessage(final FutureResponse futureResponse, final ChannelFuture close) {
    close.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture arg0) throws Exception {
            futureResponse.responseNow();
        }
    });
}

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

License:Apache License

/**
 * This test only works if the server calls "nc -lk 4000", that is done in @Before. It will open and close 1000 *
 * 1000 connections to localhost.//from www.  j  a v  a2 s.co  m
 * 
 * @throws InterruptedException .
 */
@Test
@Ignore
public void testCreatorTCP() throws InterruptedException {
    long start = System.currentTimeMillis();
    final int rounds = 10000;
    final int connections = 20;
    final int printOut = 100;
    EventLoopGroup ev = new NioEventLoopGroup();

    final int timeout = 4000;
    for (int j = 0; j < rounds; j++) {

        ChannelClientConfiguration c = PeerBuilder.createDefaultChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());

        final ChannelCreator channelCreator2 = new ChannelCreator(ev, new FutureDone<Void>(), 0, connections,
                c);
        if (j % printOut == 0) {
            System.out.print(j + " ");
        }

        final CountDownLatch countDownLatch = new CountDownLatch(connections);
        final Map<String, Pair<EventExecutorGroup, ChannelHandler>> tmp = new HashMap<String, Pair<EventExecutorGroup, ChannelHandler>>();

        final GenericFutureListener<ChannelFuture> handler = new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    future.channel().close();
                    countDownLatch.countDown();

                } else {
                    future.cause().printStackTrace();
                }
            }
        };

        for (int i = 0; i < connections; i++) {
            final ChannelFuture channelFuture = channelCreator2.createTCP(SOCKET_ADDRESS, timeout, tmp,
                    new FutureResponse(null));
            channelFuture.addListener(handler);
        }
        countDownLatch.await();
        channelCreator2.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("\nBENCHMARK: opened and closed " + connections + " x " + rounds
            + " TCP connections to localhost in " + time + " ms. STAT: TCP open/close per sec:"
            + ((connections * rounds * mil) / time));
}

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

License:Apache License

/**
 * This test only works if the server calls "nc -lku 4000", that is done in @Before.
 * /* w ww .  j  a v a  2 s .  c  o  m*/
 * @throws InterruptedException .
 */
@Test
@Ignore
public void testCreatorUDP() throws InterruptedException {
    long start = System.currentTimeMillis();
    final int rounds = 10000;
    final int connections = 20;
    final int printOut = 100;
    EventLoopGroup ev = new NioEventLoopGroup();

    for (int j = 0; j < rounds; j++) {

        ChannelClientConfiguration c = PeerBuilder.createDefaultChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        final ChannelCreator channelCreator2 = new ChannelCreator(ev, new FutureDone<Void>(), connections, 0,
                c);

        if (j % printOut == 0) {
            System.out.print(j + " ");
        }

        final CountDownLatch countDownLatch = new CountDownLatch(connections);
        final Map<String, Pair<EventExecutorGroup, ChannelHandler>> tmp = new HashMap<String, Pair<EventExecutorGroup, ChannelHandler>>();

        GenericFutureListener<ChannelFuture> handler = new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    future.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[1]));
                    future.channel().close();
                    countDownLatch.countDown();
                } else {
                    future.cause().printStackTrace();
                }
            }
        };

        for (int i = 0; i < connections; i++) {
            final ChannelFuture channelFuture = channelCreator2.createUDP(false, tmp, new FutureResponse(null));
            channelFuture.addListener(handler);
        }
        countDownLatch.await();
        channelCreator2.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("\nBENCHMARK: opened and closed " + connections + " x " + rounds
            + " UDP connections to localhost in " + time + " ms. STAT: UDP open/close per sec:"
            + ((connections * rounds * mil) / time));
}

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

License:Apache License

/**
 * Test the TCP connection reservation./*from  ww w.  j  a v  a2 s .  co  m*/
 * 
 * @throws InterruptedException .
 */

@Test
public void testReservationTCP() throws InterruptedException {
    long start = System.currentTimeMillis();
    final int round = 10;
    final int inner = 200;
    final int conn = 50;
    final int tcpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = PeerBuilder.createDefaultChannelClientConfiguration();
        c.maxPermitsTCP(tcpMax);
        c.pipelineFilter(new MyPipeLine());
        Reservation r = new Reservation(workerGroup, c);
        List<FutureChannelCreator> fcc = new ArrayList<FutureChannelCreator>();
        for (int j = 0; j < inner; j++) {
            FutureChannelCreator fc = r.create(0, conn);
            fc.addListener(new BaseFutureAdapter<FutureChannelCreator>() {
                @Override
                public void operationComplete(final FutureChannelCreator future) throws Exception {
                    final ChannelCreator cc = future.channelCreator();
                    final int timeout = 2000;
                    final CountDownLatch countDownLatch = new CountDownLatch(conn);
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createTCP(SOCKET_ADDRESS, timeout,
                                new HashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(),
                                new FutureResponse(null));
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().close();
                                countDownLatch.countDown();
                            }
                        });
                    }
                    countDownLatch.await();
                    cc.shutdown().awaitListenersUninterruptibly();
                }
            });
            fcc.add(fc);
        }
        for (FutureChannelCreator fcc1 : fcc) {
            fcc1.awaitListeners();
        }
        r.shutdown().awaitUninterruptibly();
    }
    //ev.shutdownGracefully().awaitUninterruptibly();
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("BENCHMARK: opened and closed " + round + " x " + inner + " x " + conn
            + " TCP connections to localhost in " + time + " ms. STAT: TCP res open/close per sec:"
            + ((round * inner * conn * mil) / time));
}

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

License:Apache License

/**
 * Test the TCP connection reservation. This will throw many
 * "TomP2PSinglePacketUDP - did not get the complete packet" exceptions,
 * since we are not having any proper headers.
 * //  w  w  w.j a  v  a2 s . co m
 * @throws InterruptedException .
 */
@Test
public void testReservationUDP() throws InterruptedException {
    long start = System.currentTimeMillis();
    final int round = 10;
    final int inner = 200;
    final int conn = 50;
    final int udpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = PeerBuilder.createDefaultChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        c.maxPermitsUDP(udpMax);
        Reservation r = new Reservation(workerGroup, c);
        List<FutureChannelCreator> fcc = new ArrayList<FutureChannelCreator>();
        for (int j = 0; j < inner; j++) {
            FutureChannelCreator fc = r.create(conn, 0);
            fc.addListener(new BaseFutureAdapter<FutureChannelCreator>() {
                @Override
                public void operationComplete(final FutureChannelCreator future) throws Exception {
                    final ChannelCreator cc = future.channelCreator();
                    final CountDownLatch countDownLatch = new CountDownLatch(conn);
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createUDP(false,
                                new HashMap<String, Pair<EventExecutorGroup, ChannelHandler>>() {
                                }, new FutureResponse(null));
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[1]));
                                future.channel().close();
                                countDownLatch.countDown();
                            }
                        });
                    }
                    countDownLatch.await();
                    cc.shutdown().awaitUninterruptibly();
                }
            });
            fcc.add(fc);
        }
        for (FutureChannelCreator fcc1 : fcc) {
            fcc1.awaitListeners();
        }
        r.shutdown().awaitUninterruptibly();
    }
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("BENCHMARK: opened and closed " + round + " x " + inner + " x " + conn
            + " UDP connections to localhost in " + time + " ms. STAT: UDP res open/close per sec:"
            + ((round * inner * conn * mil) / time));
}