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.alibaba.rocketmq.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public void invokeOnewayImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis)
        throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException,
        RemotingSendRequestException {/*from  w w w .  ja  v  a2  s.  c  om*/
    request.markOnewayRPC();
    boolean acquired = this.semaphoreOneway.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreOneway);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    once.release();
                    if (!f.isSuccess()) {
                        plog.warn(
                                "send a request command to channel <" + channel.remoteAddress() + "> failed.");
                        plog.warn(request.toString());
                    }
                }
            });
        } catch (Exception e) {
            once.release();
            plog.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed.");
            throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        if (timeoutMillis <= 0) {
            throw new RemotingTooMuchRequestException("invokeOnewayImpl invoke too fast");
        } else {
            String info = String.format(
                    "invokeOnewayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                    timeoutMillis, //
                    this.semaphoreAsync.getQueueLength(), //
                    this.semaphoreAsync.availablePermits()//
            );
            plog.warn(info);
            plog.warn(request.toString());
            throw new RemotingTimeoutException(info);
        }
    }
}

From source file:com.andy.grpc.proxy.HexDumpProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override// w ww .  ja  v a  2  s . com
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                future.channel().close();
            }
        }
    });
}

From source file:com.baidu.jprotobuf.pbrpc.management.HttpServer.java

License:Apache License

public void start(int port) {

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//w  w w  .ja v  a  2 s . c  o m
                public void initChannel(SocketChannel ch) throws Exception {
                    // server??httpResponse?HttpResponseEncoder?
                    ch.pipeline().addLast(new HttpResponseEncoder());
                    // serverhttpRequest?HttpRequestDecoder?
                    ch.pipeline().addLast(new HttpRequestDecoder());
                    ch.pipeline().addLast(new HttpServerInboundHandler(rpcServer));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    serverBootstrap.bind(port).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                // TODO notifyStarted();
            } else {
                // TODO notifyFailed(future.cause());
            }
        }
    });

    LOG.log(Level.INFO, "Http starting at port: " + port);
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServer.java

License:Apache License

public void start(InetSocketAddress sa) {
    LOG.log(Level.INFO, "RPC starting at: " + sa);
    this.bind(sa).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                // TODO notifyStarted();
            } else {
                // TODO notifyFailed(future.cause());
            }//from  w  w  w .j av a  2  s  .c  om
        }
    });
    this.inetSocketAddress = sa;

    startTime = System.currentTimeMillis();

    // check if need start http server
    if (rpcServerOptions.getHttpServerPort() > 0) {
        httpServer = new HttpServer(this);
        httpServer.start(rpcServerOptions.getHttpServerPort());
    }
}

From source file:com.barchart.netty.client.base.ConnectableBase.java

License:BSD License

@Override
public Observable<T> connect() {

    if (transport == null) {
        throw new IllegalArgumentException("Transport cannot be null");
    }/*  w w  w  .j a v  a2s  . c om*/

    if (channelInitializer == null) {
        throw new IllegalArgumentException("Channel initializer cannot be null");
    }

    log.debug("Client connecting to " + transport.address().toString());
    changeState(Connectable.State.CONNECTING);

    final ChannelFuture future = bootstrap() //
            .group(group) //
            .handler(new ClientPipelineInitializer()) //
            .connect();

    channel = future.channel();

    final ReplaySubject<T> connectObs = ReplaySubject.create();

    future.addListener(new ChannelFutureListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {

            if (!future.isSuccess()) {
                changeState(Connectable.State.CONNECT_FAIL);
                connectObs.onError(future.cause());
            } else {
                connectObs.onNext((T) ConnectableBase.this);
                connectObs.onCompleted();
            }

        }

    });

    return connectObs;

}

From source file:com.base.research.socket.netty.ServerHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) { // (2)
    Date date = (Date) msg;
    System.out.println("handle:" + date);

    ctx.fireChannelRead(date);//from  ww  w  .ja v  a 2 s  .  c  o m

    // ?
    long timeMillis = System.currentTimeMillis();
    final ChannelFuture f = ctx.write(timeMillis);
    ctx.flush();
    System.out.println("flush");
    // final ChannelFuture f = ctx.writeAndFlush(time); // (3)
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            assert f == future;
            ctx.close();
            System.out.println("close-----------------");
        }
    });
}

From source file:com.cdg.study.netty.time.TimeServerHandler.java

License:Open Source License

@Override
public void channelActive(final ChannelHandlerContext ctx) { // (1)
    final ByteBuf time = ctx.alloc().buffer(4); // (2)
    time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

    final ChannelFuture f = ctx.writeAndFlush(time); // (3)
    f.addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) {
            assert f == future;
            ctx.close();// www . java  2 s . co m
        }
    }); // (4)
}

From source file:com.chenyang.proxy.http.HttpRelayHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    if (relayChannel.isActive()) {
        relayChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override//from   www . ja  va2  s.  c  o m
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!ctx.channel().config().getOption(ChannelOption.AUTO_READ)) {
                    ctx.read();
                }
            }
        });
    } else {
        ReferenceCountUtil.release(msg);
    }

}

From source file:com.chenyang.proxy.http.HttpRemoteForwardHandler.java

License:Apache License

public void channelRead(final ChannelHandlerContext remoteChannelCtx, final Object msg) throws Exception {

    remainMsgCount++;/*from   w w w . jav a 2s .com*/

    if (remainMsgCount <= 5) {
        remoteChannelCtx.read();
    }

    HttpObject ho = (HttpObject) msg;

    if (ho instanceof HttpResponse) {
        HttpResponse httpResponse = (HttpResponse) ho;

        httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        httpResponse.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE);
    }

    if (uaChannel.isActive()) {
        uaChannel.writeAndFlush(ho).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    remainMsgCount--;
                    remoteChannelCtx.read();
                } else {
                    remoteChannelCtx.close();
                }
            }
        });
    } else {
        remoteChannelCtx.close();
    }
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {// w ww  . j  ava2 s  .co  m

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}