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.tomp2p.connection2.TestReservation.java

License:Apache License

/**
 * Test the TCP connection reservation.// w w w  . jav a2  s.co m
 * 
 * @throws InterruptedException .
 */
@Test
public void testReservationTCP() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    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 = new ChannelClientConfiguration();
        c.maxPermitsTCP(tcpMax);
        c.pipelineFilter(new MyPipeLine());
        Reservation r = new Reservation(ev, 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.getChannelCreator();
                    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, ChannelHandler>());
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().close();
                                countDownLatch.countDown();
                            }
                        });
                    }
                    countDownLatch.await();
                    cc.shutdown().awaitUninterruptibly();
                }
            });
            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.connection2.TestReservation.java

License:Apache License

/**
 * Test the TCP connection reservation./*from w  ww  .  ja  v  a2s  . c  o m*/
 * 
 * @throws InterruptedException .
 */
@Test
public void testReservationUDP() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    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 = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        c.maxPermitsUDP(udpMax);
        Reservation r = new Reservation(ev, 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.getChannelCreator();
                    final CountDownLatch countDownLatch = new CountDownLatch(conn);
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createUDP(SOCKET_ADDRESS, false,
                                new HashMap<String, ChannelHandler>() {
                                });
                        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();
    }
    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
            + " UDP connections to localhost in " + time + " ms. STAT: UDP res open/close per sec:"
            + ((round * inner * conn * mil) / time));
}

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

License:Apache License

/**
 * Test an unclean shutdown, that means the reservation is shutdown, but the connectioncreation is not.
 * //from  w  w  w .j  ava 2s . c o  m
 * @throws InterruptedException .
 */
@Test
public void testReservationTCPNonCleanShutdown() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    long start = System.currentTimeMillis();
    final int round = 50;
    final int inner = 100;
    final int conn = 10;
    final int tcpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        c.maxPermitsTCP(tcpMax);
        Reservation r = new Reservation(ev, 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 {
                    if (future.isFailed()) {
                        return;
                    }
                    final ChannelCreator cc = future.getChannelCreator();
                    final int timeout = 2000;
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createTCP(SOCKET_ADDRESS, timeout,
                                new HashMap<String, ChannelHandler>() {
                                });
                        if (channelFuture == null) {
                            return;
                        }
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().close();
                            }
                        });
                    }
                }
            });
            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 unclean open/close per sec:"
            + ((round * inner * conn * mil) / time));
}

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

License:Apache License

/**
 * Unclean shutdown of pending connections.
 * /* www  .j  ava 2s  .com*/
 * @throws InterruptedException .
 */
@Test
public void testReservationTCPNonCleanShutdown2() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    final int round = 50;
    final int inner = 100;
    final int conn = 10;
    final int tcpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        c.maxPermitsTCP(tcpMax);
        Reservation r = new Reservation(ev, 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 {
                    if (future.isFailed()) {
                        return;
                    }
                    final ChannelCreator cc = future.getChannelCreator();
                    final int timeout = 2000;
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createTCP(SOCKET_ADDRESS, timeout,
                                new HashMap<String, ChannelHandler>() {
                                });
                        if (channelFuture == null) {
                            return;
                        }
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().close();
                            }
                        });
                    }
                }
            });
            fcc.add(fc);
        }
        r.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
}

From source file:net.tomp2p.rpc.PingRPC.java

License:Apache License

/**
 * Ping a peer, and request the other peer to return the source port of our
 * socket used to send the message. This method needs to do the setup of a
 * ChannelFuture manually since we need to know the port number of the
 * assigned socket.// w  w  w.  j  a  va 2 s .c  om
 * 
 * @param remotePeer
 *            The destination peer
 * @param channelCreator
 *            The channel creator where we create a UPD channel
 * @return The future that will be triggered when we receive an answer or
 *         something fails.
 */
public FutureDone<List<PeerSocketAddress>> pingNATType(final PeerAddress remotePeer,
        final ChannelCreator channelCreator, final ConnectionConfiguration configuration, final Peer peer) {
    final FutureDone<List<PeerSocketAddress>> fDone = new FutureDone<List<PeerSocketAddress>>();
    final List<PeerSocketAddress> peerSocketAddresses = new ArrayList<PeerSocketAddress>(2);
    final Message message = createMessage(remotePeer, RPC.Commands.PING.getNr(), Type.REQUEST_5);
    final FutureResponse futureResponse = new FutureResponse(message);
    final SimpleChannelInboundHandler<Message> inbound = new SimpleChannelInboundHandler<Message>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
            if (!msg.peerSocketAddresses().isEmpty() && msg.type() == Type.OK) {
                peerSocketAddresses.add(msg.peerSocketAddresses().get(0));
                fDone.done(peerSocketAddresses);
                ctx.close();
            }
        }
    };
    Utils.addReleaseListener(channelCreator, futureResponse);
    final ChannelFuture cF = channelCreator.createUDP(false,
            peer.connectionBean().sender().configureHandlers(inbound, futureResponse, 30, false),
            futureResponse);
    cF.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                InetSocketAddress srcAddress = (InetSocketAddress) future.channel().localAddress();
                peerSocketAddresses.add(new PeerSocketAddress(srcAddress.getAddress(), srcAddress.getPort(),
                        srcAddress.getPort()));
                peer.connectionBean().sender().afterConnect(futureResponse, message, future, false);
            }
        }
    });
    return fDone;
}

From source file:Netty.BeaconServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    // Generate and write a response.
    String response;/*from w  w w . j  a va  2 s  .c o  m*/
    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;
        stop = true;
    } else {
        response = "Did you say '" + request + "'?\r\n";
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at BeaconPipelineFactory 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:netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    if (!msg.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/* ww w  . jav  a  2 s.  co m*/
        return;
    }
    if (msg.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final String uri = msg.getUri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");// ??
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = randomAccessFile.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    if (isKeepAlive(msg)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ChannelFuture sendFileFuture;
    sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192),
            ctx.newProgressivePromise());
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.out.println("Transfer complete.");
        }
    });
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(msg)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:netty.protocol.http.xml.server.HttpXmlServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpXmlRequest msg) throws Exception {
    HttpRequest request = msg.getRequest();
    Order order = (Order) msg.getBody();
    System.out.println("Http server receive request : " + order);
    dobusiness(order);//from w  w w .  j  a va  2  s  .  c o m
    ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
    if (!isKeepAlive(request)) {
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future future) throws Exception {
                ctx.close();
            }
        });
    }
}

From source file:netty.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest 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);/*  ww w. jav  a2 s.co  m*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
        //            System.out.println( "sendHttpResponse = " + res);
    }

    // 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:netty.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(final ChannelHandlerContext ctx, final FullHttpRequest req,
        final FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status() != HttpResponseStatus.OK) {
        final ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*  w  w  w  . j  a v  a 2  s .co  m*/
        buf.release();
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

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