Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener

Introduction

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

Prototype

ChannelFutureListener

Source Link

Usage

From source file:com.xx_dev.apn.socks.remote.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from   w  ww .ja va2 s  .  c o  m*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                restLogger.info(request.host() + ":" + request.port() + "," + "T");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .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 {
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                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.host(), request.port()).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.
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.xx_dev.port_forwared.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendInitializer(inboundChannel, remoteSsl))
            .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();//  w  ww . j  a v a 2 s  .  c  o m
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.xyz.rpc.netty4.server.Netty4ServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, RequestWrapper request) throws Exception {
    long beginTime = System.currentTimeMillis();
    ResponseWrapper responseWrapper = ProtocolFactory.getServerHandler(request.getProtocolType())
            .handleRequest(request);//  w  w  w .j  a  v a 2 s  . c  o  m
    final int id = request.getId();
    // already timeout,so not return
    if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) {
        LOGGER.warn("timeout,so give up send response to client,requestId is:" + id + ",client is:"
                + ctx.channel().remoteAddress() + ",consumetime is:" + (System.currentTimeMillis() - beginTime)
                + ",timeout is:" + request.getTimeout());
        return;
    }
    ChannelFuture wf = ctx.channel().writeAndFlush(responseWrapper);
    wf.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                LOGGER.error("server write response error,request id is: " + id);
            }
        }
    });
}

From source file:com.zaradai.distributor.messaging.netty.ChannelConnection.java

License:Apache License

@Override
protected void doSend(final Message message) throws MessagingException {
    channel.writeAndFlush(message).addListener(new ChannelFutureListener() {
        @Override/*from   w  w w .j  a v  a 2s. c om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                onSuccess(message);
            } else {
                onFailure(message, future.cause());
            }
        }
    });
}

From source file:com.zaradai.distributor.messaging.netty.NettyClient.java

License:Apache License

private void connect(final RetryPolicy retryPolicy) {
    ChannelFuture future = bootstrap.connect(endpoint);
    future.addListener(new ChannelFutureListener() {
        @Override/*from   w  w  w.jav a  2 s  .  c  om*/
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final ChannelFuture fut = channelFuture;

            if (channelFuture.isSuccess()) {
                connected();
            } else {
                eventLoopGroups.getClientGroup().submit(new Runnable() {
                    @Override
                    public void run() {
                        if (retryPolicy.retry()) {
                            connect(retryPolicy);
                        } else {
                            failed(fut.cause());
                        }
                    }
                });
            }
        }
    });
}

From source file:com.zextras.modules.chat.server.xmpp.netty.StanzaWriterImp.java

License:Open Source License

@Override
public void onEventQueued(EventQueue eventQueue) {
    try {// w  w  w. j  a  v a 2  s .c om
        final ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
        for (Event event : eventQueue.popAllEvents()) {
            LogContext logContext = CurrentLogContext.begin();
            if (event.getTarget().getAddresses().size() == 1) {
                logContext.setAccountName(event.getTarget().toSingleAddress());
            }
            logContext.freeze();
            try {
                out.reset();
                XmppEncoder encoder = (XmppEncoder) event.interpret(mEncoderFactory);
                if (encoder == null) {
                    ChatLog.log.debug("No encoder found for event " + event.getClass().getName());
                    continue;
                }

                final SpecificAddress exposedAddress = mXmppConnectionHandler.getSession().getExposedAddress();

                encoder.encode(out, exposedAddress);

                String stanzaDebug = new String(out.toByteArray(), "UTF-8");
                ChatLog.log.debug("writing: " + event.getClass().getName());
                ChatLog.log.debug("writing stanza(" + stanzaDebug.length() + "): " + stanzaDebug);
                ByteBuf stanza = Unpooled.copiedBuffer(out.toByteArray());
                ChannelFuture writeFuture = mXmppConnectionHandler.write(stanza);

                final Event eventToNotify = event;

                writeFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            EventInterceptor interceptor = eventToNotify
                                    .interpret(mXmppEventInterceptorFactory);
                            interceptor.intercept(mEventManager, exposedAddress);
                        }
                    }
                });
            } finally {
                CurrentLogContext.end();
            }
        }
    } catch (Throwable ex) {
        ChatLog.log.warn("Exception: " + Utils.exceptionToString(ex));
    }
}

From source file:com.zextras.modules.chat.server.xmpp.netty.TransparentProxy.java

License:Open Source License

public Future<Channel> connect() {
    final Promise<Channel> channelFuture = new DefaultProgressivePromise<Channel>(
            ImmediateEventExecutor.INSTANCE);

    if (mServerChannel == null) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(mNettyService.getEventLoopGroup()).channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(mAccount.getMailHost(), mPort)).handler(new Initializer());

        ChannelFuture serverChannelFuture = bootstrap.connect();
        serverChannelFuture.addListener(new ChannelFutureListener() {
            @Override//from   w w w  .  j  av  a  2  s .co m
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ChatLog.log.info(
                            "Proxy xmpp requests for " + mAccount.getName() + " to " + mAccount.getMailHost());
                    mServerChannel = future.channel();

                    mServerChannel.write(Unpooled.wrappedBuffer(mStreamInit.getBytes()));
                    mServerChannel.writeAndFlush(Unpooled.wrappedBuffer(mInitialPayload.getBytes()));

                    mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

                    mClientChannel.pipeline().addLast("proxyToServer", new Proxy(mServerChannel));

                    mServerChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mClientChannel.close();
                        }
                    });

                    mClientChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mServerChannel.close();
                        }
                    });

                    future.channel().closeFuture();

                    channelFuture.setSuccess(mServerChannel);
                } else {
                    ChatLog.log.info("Cannot proxy xmpp requests for " + mAccount.getName() + " to "
                            + mAccount.getMailHost() + ": " + Utils.exceptionToString(future.cause()));
                    sendInternalError(mClientChannel);
                    mClientChannel.flush().close();
                    channelFuture.setFailure(future.cause());
                }
            }
        });

        return channelFuture;
    } else {
        mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

        mServerChannel.writeAndFlush(mInitialPayload.getBytes());

        channelFuture.setSuccess(mServerChannel);
        return channelFuture;
    }
}

From source file:com.zhang.pool.NettyChannelPool.java

License:Apache License

private boolean sendRequestUseNewChannel(final InetSocketAddress route, final HttpRequest request,
        final NettyHttpResponseFuture responseFuture, boolean forceConnect) {
    ChannelFuture future = createChannelFuture(route, forceConnect);
    if (null != future) {
        NettyHttpResponseFutureUtil.attributeResponse(future.channel(), responseFuture);
        NettyHttpResponseFutureUtil.attributeRoute(future.channel(), route);
        future.addListener(new ChannelFutureListener() {

            @Override/*from   w  w w. j  a  va2s.co m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {

                    future.channel().closeFuture().addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {

                            logger.log(Level.SEVERE,
                                    future.channel() + " closed, exception: " + future.cause());
                            removeChannel(future.channel(), future.cause());
                        }

                    });
                    future.channel().writeAndFlush(request).addListener(CLOSE_ON_FAILURE);
                } else {
                    logger.log(Level.SEVERE,
                            future.channel() + " connect failed, exception: " + future.cause());

                    NettyHttpResponseFutureUtil.cancel(future.channel(), future.cause());
                    if (!NettyHttpResponseFutureUtil.getForceConnect(future.channel())) {
                        releaseCreatePerRoute(future.channel());
                    }
                }
            }

        });
        return true;
    }
    return false;
}

From source file:com.zhucode.longio.transport.netty.NettyClient.java

License:Open Source License

@Override
public void send(MessageBlock mb) {
    long sid = channel.attr(NettyConnector.sessionKey).get();
    mb.setSessionId(sid);/* w ww .ja va 2s  . c  o  m*/
    ChannelFuture f = this.connector.send(mb);
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isCancelled() || future.cause() != null) {
                throw new Exception("service maybe unavailable");
            }
        }
    });

}

From source file:de.cubeisland.engine.core.webapi.WebSocketRequestHandler.java

License:Open Source License

public void doHandshake(ChannelHandlerContext ctx, FullHttpRequest message) {
    WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory(
            "ws://" + message.headers().get(HOST) + "/" + this.WEBSOCKET_ROUTE, null, false);
    this.handshaker = handshakerFactory.newHandshaker(message);
    if (handshaker == null) {
        this.log.info("client is incompatible!");
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
        return;//  w  ww. ja v  a 2 s .  co m
    }
    this.log.debug("handshaking now...");
    this.handshaker.handshake(ctx.channel(), message).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                log.debug("Success!");
            } else {
                log.debug("Failed!");
            }
        }
    });
}