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.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void writeAsync(final List<ByteBuf> buffers, final AsyncCompletionHandler<Void> handler) {
    CompositeByteBuf composite = PooledByteBufAllocator.DEFAULT.compositeBuffer();
    for (ByteBuf cur : buffers) {
        io.netty.buffer.ByteBuf byteBuf = ((NettyByteBuf) cur).asByteBuf();
        composite.addComponent(byteBuf.retain());
        composite.writerIndex(composite.writerIndex() + byteBuf.writerIndex());
    }/*w  ww . j a  va 2s.  c  om*/

    channel.writeAndFlush(composite).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handler.failed(future.cause());
            } else {
                handler.completed(null);
            }
        }
    });
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public void processRequestCommand(final ChannelHandlerContext ctx, final RemotingCommand cmd) {
    final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode());
    final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessor
            : matched;//from   w w  w .j  a va2  s.  co m

    if (pair != null) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    RPCHook rpcHook = NettyRemotingAbstract.this.getRPCHook();
                    if (rpcHook != null) {
                        rpcHook.doBeforeRequest(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd);
                    }

                    final RemotingCommand response = pair.getObject1().processRequest(ctx, cmd);
                    if (rpcHook != null) {
                        rpcHook.doAfterResponse(cmd, response);
                    }

                    // Oneway?
                    if (!cmd.isOnewayRPC()) {
                        if (response != null) {
                            response.setOpaque(cmd.getOpaque());
                            response.markResponseType();
                            try {
                                ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
                                    @Override
                                    public void operationComplete(ChannelFuture future) throws Exception {
                                        if (!future.isSuccess()) {
                                            plog.error("response to "
                                                    + RemotingHelper.parseChannelRemoteAddr(future.channel())
                                                    + " failed", future.cause());
                                            plog.error(cmd.toString());
                                            plog.error(response.toString());
                                        }
                                    }
                                });
                            } catch (Throwable e) {
                                plog.error("process request over, but response failed", e);
                                plog.error(cmd.toString());
                                plog.error(response.toString());
                            }
                        } else {
                            // ?processRequest?
                        }
                    }
                } catch (Throwable e) {
                    plog.error("process request exception", e);
                    plog.error(cmd.toString());

                    if (!cmd.isOnewayRPC()) {
                        final RemotingCommand response = RemotingCommand.createResponseCommand(
                                RemotingSysResponseCode.SYSTEM_ERROR, //
                                RemotingHelper.exceptionSimpleDesc(e));
                        response.setOpaque(cmd.getOpaque());
                        ctx.writeAndFlush(response);
                    }
                }
            }
        };

        try {
            // ??????
            pair.getObject2().submit(run);
        } catch (RejectedExecutionException e) {
            plog.warn(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) //
                    + ", too many requests and system thread pool busy, RejectedExecutionException " //
                    + pair.getObject2().toString() //
                    + " request code: " + cmd.getCode());
            if (!cmd.isOnewayRPC()) {
                final RemotingCommand response = RemotingCommand.createResponseCommand(
                        RemotingSysResponseCode.SYSTEM_BUSY,
                        "too many requests and system thread pool busy, please try another server");
                response.setOpaque(cmd.getOpaque());
                ctx.writeAndFlush(response);
            }
        }
    } else {
        String error = " request type " + cmd.getCode() + " not supported";
        final RemotingCommand response = RemotingCommand
                .createResponseCommand(RemotingSysResponseCode.REQUEST_CODE_NOT_SUPPORTED, error);
        response.setOpaque(cmd.getOpaque());
        ctx.writeAndFlush(response);
        plog.error(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) + error);
    }
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis,
        final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException,
        RemotingTimeoutException, RemotingSendRequestException {
    boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync);

        final ResponseFuture responseFuture = new ResponseFuture(request.getOpaque(), timeoutMillis,
                invokeCallback, once);//from   www.  j av a 2 s.  c o m
        this.responseTable.put(request.getOpaque(), responseFuture);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    if (f.isSuccess()) {
                        responseFuture.setSendRequestOK(true);
                        return;
                    } else {
                        responseFuture.setSendRequestOK(false);
                    }

                    responseFuture.putResponse(null);
                    responseFuture.executeInvokeCallback();

                    responseTable.remove(request.getOpaque());
                    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("invokeAsyncImpl invoke too fast");
        } else {
            plog.warn("invokeAsyncImpl tryAcquire semaphore timeout, " + timeoutMillis
                    + " waiting thread nums: " + this.semaphoreAsync.getQueueLength());
            plog.warn(request.toString());

            throw new RemotingTimeoutException("tryAcquire timeout(ms) " + timeoutMillis);
        }
    }
}

From source file:com.moshi.receptionist.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   ww w.j av a2 s  .  com
    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 {
            plog.warn("invokeOnewayImpl tryAcquire semaphore timeout, " + timeoutMillis
                    + " waiting thread nums: " + this.semaphoreOneway.getQueueLength());
            plog.warn(request.toString());

            throw new RemotingTimeoutException("tryAcquire timeout(ms) " + timeoutMillis);
        }
    }
}

From source file:com.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override/* w ww.ja va 2  s.c o  m*/
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}

From source file:com.mpush.netty.server.NettyServer.java

License:Apache License

private void createServer(final Listener listener, EventLoopGroup boss, EventLoopGroup work,
        Class<? extends ServerChannel> clazz) {
    /***/*from ww  w. j  av a2s .c o m*/
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channel(clazz);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        ChannelFuture f = b.bind(port).sync().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    Logs.Console.error("server start success on:{}", port);
                    if (listener != null)
                        listener.onSuccess(port);
                } else {
                    Logs.Console.error("server start failure on:{}", port, future.cause());
                    if (listener != null)
                        listener.onFailure(future.cause());
                }
            }
        });
        if (f.isSuccess()) {
            serverState.set(State.Started);
            /**
             * socket
             */
            f.channel().closeFuture().sync();
        }

    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    } finally {
        /***
         * 
         */
        stop(null);
    }
}

From source file:com.mycompany.device.FFDevice.java

public FFDevice(SocketChannel ch) {
    this.req = null;
    this.soc = ch;
    this.data_rcv = soc.alloc().buffer(512);
    this.reg_str = "";
    this.connect_time = System.currentTimeMillis();

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(0, 0, idle_time_interval_s));
    pipeline.addLast(new MessageToByteEncoder<byte[]>() {
        @Override/*from www.  j a  v a 2 s.  c o  m*/
        protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
            // TODO Auto-generated method stub
            out.writeBytes(msg);
        }
    });
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // TODO Auto-generated method stub
            ByteBuf bb = (ByteBuf) msg;
            if (reg_str.equals("")) {
                reg_str = bb.toString(Charset.defaultCharset());
                FFServer.logger.info(String.format("device that has regs %s is registed", reg_str));
            } else {
                FFServer.logger.debug(String.format("%s receive: %d bytes", reg_str, bb.readableBytes()));
                data_rcv.writeBytes(bb);
            }
            ReferenceCountUtil.release(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // TODO Auto-generated method stub
            FFServer.logger.error(cause);
            Close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.ALL_IDLE) {
                    FFServer.logger.info(String.format("%s in idle state", reg_str));

                    ByteBuf hb = ctx.alloc().buffer(1).writeByte('.');
                    Send(hb);
                }
            }
        }
    });

    ChannelFuture f = soc.closeFuture();
    f.addListener((ChannelFutureListener) new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            is_closed = true;
            FFServer.logger.info(String.format("%s disconnected", reg_str));
        }
    });
}

From source file:com.navercorp.nbasearc.gcp.PhysicalConnection.java

License:Apache License

SettableFuture<Boolean> connect() {
    state.set(State.CONNECTING);//from   w ww.  j a  v a 2s. c  om
    final SettableFuture<Boolean> sf = SettableFuture.create();
    b.connect(ip, port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            connectionComplete(cf);

            if (cf.cause() != null) {
                sf.setException(cf.cause());
            } else {
                sf.set(true);
            }
        }
    });
    return sf;
}

From source file:com.navercorp.pinpoint.plugin.netty.NettyIT.java

License:Apache License

@Test
public void writeTest() throws Exception {
    final CountDownLatch awaitLatch = new CountDownLatch(1);

    Bootstrap bootstrap = client();/*from w w w  .  j a  va2s .co  m*/
    bootstrap.connect(webServer.getHostname(), webServer.getListeningPort())
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        Channel channel = future.channel();
                        channel.pipeline().addLast(new SimpleChannelInboundHandler() {

                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, Object msg)
                                    throws Exception {
                                awaitLatch.countDown();
                            }

                        });
                        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                                "/");
                        future.channel().writeAndFlush(request);
                    }
                }

            });

    boolean await = awaitLatch.await(3000, TimeUnit.MILLISECONDS);
    Assert.assertTrue(await);

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    verifier.verifyTrace(event("NETTY", Bootstrap.class.getMethod("connect", SocketAddress.class),
            annotation("netty.address", webServer.getHostAndPort())));
    verifier.verifyTrace(event("NETTY",
            "io.netty.channel.DefaultChannelPromise.addListener(io.netty.util.concurrent.GenericFutureListener)"));
    verifier.verifyTrace(event("ASYNC", "Asynchronous Invocation"));
    verifier.verifyTrace(
            event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListenersNow()"));
    verifier.verifyTrace(event("NETTY_INTERNAL",
            "io.netty.util.concurrent.DefaultPromise.notifyListener0(io.netty.util.concurrent.Future, io.netty.util.concurrent.GenericFutureListener)"));
    verifier.verifyTrace(
            event("NETTY", "io.netty.channel.DefaultChannelPipeline.writeAndFlush(java.lang.Object)"));
    verifier.verifyTrace(event("NETTY_HTTP",
            "io.netty.handler.codec.http.HttpObjectEncoder.encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)",
            annotation("http.url", "/")));
}

From source file:com.netflix.custom.client.ClientHandler.java

License:Apache License

private void sendNextMessage(Attribute msgToSend, ChannelHandlerContext ctx) {
    if (!waitingForReply.compareAndSet(false, true)) {
        logger.error(/*from   w  w  w. j av a 2s  .co  m*/
                "Client can not send a command when the response from the last command is not finished. Last command sent: "
                        + lastCommandSent);
        return;
    }
    final String attribName = msgToSend.name();
    lastCommandSent = attribName;
    ctx.writeAndFlush(msgToSend).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                System.out.println("> " + attribName);
            }
            logger.info(String.format("Message sent to the server. Future result, success? %s",
                    future.isSuccess()));
        }
    });
}