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:com.look.netty.demo.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override//w w w .ja  va2 s .c  om
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, request.dstAddrType()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.lxz.talk.websocketx.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);//from w  w w .jav  a2 s. c  om
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);

    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.magnet.yak.load.XMPPHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) { // (1)

    String s = "<stream:stream to=\"54.148.43.16\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">\"\r\n";
    final ByteBuf str = ctx.alloc().buffer(s.getBytes().length); // (2)
    str.writeBytes(s.getBytes());/*ww w  .  ja  va 2s  .c  o  m*/
    LOGGER.trace("channelActive : {}");
    final ChannelFuture f = ctx.writeAndFlush(str);
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture arg0) throws Exception {
            LOGGER.trace("operationComplete : {}");
        }

    });
    /*final ChannelFuture f = ctx.writeAndFlush(time); // (3)
    f.addListener(new ChannelFutureListener() {
     public void operationComplete(ChannelFuture arg0) throws Exception {
            
     }
            
    }); */// (4)
}

From source file:com.mastfrog.acteur.Application.java

License:Open Source License

protected void send404(RequestID id, Event<?> event, Channel channel) {
    HttpResponse response = createNotFoundResponse(event);
    onBeforeRespond(id, event, response.getStatus());
    ChannelFutureListener closer = !ResponseImpl.isKeepAlive(event) ? ChannelFutureListener.CLOSE : null;
    ChannelFuture fut = channel.writeAndFlush(response);
    if (closer != null) {
        fut.addListener(closer);
    }//  w  w w .j  av a2  s .co  m
}

From source file:com.mastfrog.acteur.io.FileWriter.java

License:Open Source License

@Override
public void operationComplete(ChannelFuture f) throws Exception {
    if (!f.channel().isOpen()) {
        return;/*w  ww  .j  ava  2  s .co m*/
    }
    ByteBuf buf = f.channel().alloc().buffer(bufferSize);
    int bytes = buf.writeBytes(stream, bufferSize);
    if (bytes == -1) {
        stream.close();
        f.channel().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(CLOSE);
        return;
    }
    f = f.channel().writeAndFlush(new DefaultHttpContent(buf));
    f.addListener(this);
}

From source file:com.mastfrog.acteur.ResponseImpl.java

License:Open Source License

ChannelFuture sendMessage(Event<?> evt, ChannelFuture future, HttpMessage resp) {
    if (listener != null) {
        future = future.addListener(listener);
        return future;
    } else if (!isKeepAlive(evt)) {
        future = future.addListener(ChannelFutureListener.CLOSE);
    }/*from  ww w  .ja  va  2s  . c  o  m*/
    return future;
}

From source file:com.mastfrog.netty.http.client.HttpClient.java

License:Open Source License

private void submit(final URL url, HttpRequest rq, final AtomicBoolean cancelled, final ResponseFuture handle,
        final ResponseHandler<?> r, RequestInfo info, Duration timeout, boolean noAggregate) {
    if (info != null && info.isExpired()) {
        cancelled.set(true);/*from   w ww  . j  ava2 s.com*/
    }
    if (cancelled.get()) {
        handle.event(new State.Cancelled());
        return;
    }
    try {
        for (RequestInterceptor i : interceptors) {
            rq = i.intercept(rq);
        }
        final HttpRequest req = rq;
        Bootstrap bootstrap;
        if (url.getProtocol().isSecure()) {
            bootstrap = startSsl(url.getHostAndPort());
        } else {
            bootstrap = start(url.getHostAndPort());
        }
        if (!url.isValid()) {
            throw new IllegalArgumentException(url.getProblems() + "");
        }
        TimeoutTimerTask tt = null;
        if (info == null) {
            info = new RequestInfo(url, req, cancelled, handle, r, timeout, tt, noAggregate);
            if (timeout != null) {
                tt = new TimeoutTimerTask(cancelled, handle, r, info);
                timer.schedule(tt, timeout.getMillis());
            }
            info.timer = tt;
        }
        if (info.isExpired()) {
            handle.event(new State.Timeout(info.age()));
            return;
        }
        handle.event(new State.Connecting());
        //XXX who is escaping this?
        req.setUri(req.getUri().replaceAll("%5f", "_"));
        ChannelFuture fut = bootstrap.connect(url.getHost().toString(), url.getPort().intValue());
        if (tt != null) {
            fut.channel().closeFuture().addListener(tt);
        }
        fut.channel().attr(KEY).set(info);
        handle.setFuture(fut);
        if (!monitors.isEmpty()) {
            for (ActivityMonitor m : monitors) {
                m.onStartRequest(url);
            }
            fut.channel().closeFuture().addListener(new AdapterCloseNotifier(url));
        }

        fut.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        cause = new ConnectException(url.getHost().toString());
                    }
                    handle.event(new State.Error(cause));
                    if (r != null) {
                        r.onError(cause);
                    }
                    cancelled.set(true);
                }
                if (cancelled.get()) {
                    future.cancel(true);
                    if (future.channel().isOpen()) {
                        future.channel().close();
                    }
                    for (ActivityMonitor m : monitors) {
                        m.onEndRequest(url);
                    }
                    return;
                }
                handle.event(new State.Connected(future.channel()));
                handle.event(new State.SendRequest(req));
                future = future.channel().writeAndFlush(req);
                future.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (cancelled.get()) {
                            future.cancel(true);
                            future.channel().close();
                        }
                        handle.event(new State.AwaitingResponse());
                    }

                });
            }

        });
    } catch (Exception ex) {
        Exceptions.chuck(ex);
    }
}

From source file:com.mastfrog.scamper.SctpClient.java

License:Open Source License

/**
 * Start the client, returning a ChannelFuture which can be waited on to
 * keep the client running (the returned future is the client SCTP socket's
 * channel's <code>closeFuture()</code> - call its <code>sync()</code>
 * method to block the current thread until the connection is closed.
 *
 * @return The close future for this client's connection
 * @throws InterruptedException if the connect process is interrupted
 *//*from w ww  . j a v a2  s .c om*/
public ChannelFuture start() throws InterruptedException {
    // Configure the client.
    Bootstrap b = new Bootstrap();

    configurer.init(b).handler(new LoggingHandler(LogLevel.INFO));

    logger.log(Level.INFO, "Start for {0} on {1}", new Object[] { host, port });
    // Start the client.
    ChannelFuture f = b.connect(host, port);
    if (logger.isLoggable(Level.FINE)) {
        f.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                logger.log(Level.FINE, "Connect to {0}:{1}", new Object[] { host, port });
            }

        });
    }
    f.sync();
    // Caller can until the connection is closed.
    return f.channel().closeFuture();
}

From source file:com.mastfrog.scamper.SctpServer.java

License:Open Source License

public ChannelFuture start(AtomicReference<ChannelFuture> connectFutureReceiver) throws InterruptedException {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    config.init(b);/*from   w ww.j  av  a  2  s .  co m*/
    b.handler(new LoggingHandler(LogLevel.INFO));

    logger.log(Level.FINE, "Start server on {0}", port);
    // Start the server.
    ChannelFuture f = b.bind(port);
    if (logger.isLoggable(Level.FINE)) {
        f.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                logger.log(Level.FINE, "Listening for connections on {0}", port);
            }

        });
    }
    f.sync();
    logger.log(Level.FINER, "Thread proceeding", Thread.currentThread());
    // For tests and things that need to delay execution until a connection
    // has been opened
    if (connectFutureReceiver != null) {
        connectFutureReceiver.set(f);
    }
    synchronized (this) {
        return future = f.channel().closeFuture();
    }
}

From source file:com.mastfrog.scamper.Sender.java

License:Open Source License

/**
 * Send a message using the passed channel.
 *
 * @param channel The channel/* ww  w  . j  a v a  2 s.co  m*/
 * @param message A future which will be notified when the message is
 * flushed to the socket
 * @param sctpChannel The ordinal of the sctp channel
 * @return a future that will be notified when the message write is
 * completed
 * @throws IOException if something goes wrong
 */
@SuppressWarnings("unchecked")
public ChannelFuture send(Channel channel, final Message<?> message, int sctpChannel) throws IOException {
    Checks.notNull("channel", channel);
    Checks.notNull("message", message);
    Checks.nonNegative("sctpChannel", sctpChannel);
    ByteBufAllocator alloc = channel.alloc();
    ByteBuf outbound = alloc.buffer();
    if (message.body != null) {
        if (message.body instanceof ByteBuf) {
            outbound = (ByteBuf) message.body;
        } else {
            outbound = alloc.buffer();
            try (ByteBufOutputStream out = new ByteBufOutputStream(outbound)) {
                mapper.writeValue(message.body, out);
            }
        }
    }
    ByteBuf encodedBuffer = encoder.encode(message.type, outbound, channel);
    NioSctpChannel ch = (NioSctpChannel) channel;
    if (!ch.isOpen()) {
        return ch.newFailedFuture(new ClosedChannelException());
    }
    if (ch.association() == null) {
        return channel.newFailedFuture(new IOException("Association closed - client has disconnected"));
    }
    MessageInfo info = MessageInfo.createOutgoing(ch.association(), ch.remoteAddress(), sctpChannel);
    info.unordered(true);

    SctpMessage sctpMessage = new SctpMessage(info, encodedBuffer);
    logger.log(Level.FINE, "Send message to {0} type {1}",
            new Object[] { channel.remoteAddress(), message.type });
    ChannelFuture result = channel.writeAndFlush(sctpMessage);
    if (logger.isLoggable(Level.FINER)) {
        result.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.cause() != null) {
                    logger.log(Level.SEVERE, "Send to " + ch.remoteAddress() + " failed", future.cause());
                } else {
                    logger.log(Level.FINER, "Send completed to {0}", ch.remoteAddress());
                }
            }

        });
    }
    return result;
}