Example usage for io.netty.channel ChannelFuture isSuccess

List of usage examples for io.netty.channel ChannelFuture isSuccess

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:com.mpush.core.push.SingleUserPushTask.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (checkTimeout())
        return;//  w  w w  .j av  a  2 s .  c  o  m

    if (future.isSuccess()) {//??

        if (message.isNeedAck()) {//?ACK, ?ACK
            addAckTask(messageId);
        } else {
            PushCenter.I.getPushListener().onSuccess(message, timeLine.successEnd().getTimePoints());
        }

        Logs.PUSH.info("[SingleUserPush] push message to client success, timeLine={}, message={}", timeLine,
                message);

    } else {//?

        PushCenter.I.getPushListener().onFailure(message, timeLine.failureEnd().getTimePoints());

        Logs.PUSH.error("[SingleUserPush] push message to client failure, message={}, conn={}", message,
                future.channel());
    }
}

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/*from   w w w .j  av  a  2s .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.connection.NettyConnection.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        lastWriteTime = System.currentTimeMillis();
    } else {//from w  w w  .ja  v a 2s . c  om
        LOGGER.error("connection send msg error", future.cause());
        Logs.CONN.error("connection send msg error={}, conn={}", future.cause().getMessage(), this);
    }
}

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 .ja  v a 2 s.c om
     * 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.navercorp.pinpoint.plugin.netty.NettyIT.java

License:Apache License

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

    Bootstrap bootstrap = client();//w  w w  .ja v a  2 s. c  o  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.necla.simba.server.gateway.server.backend.BackendConnector.java

License:Apache License

public void connect(Properties props, List<String> backends, SubscriptionManager subscriptionManager,
        ClientAuthenticationManager cam) throws URISyntaxException, IOException {
    this.subscriptionManager = subscriptionManager;
    this.cam = cam;
    hasher = new ConsistentHash(backends);

    int nthreads = Integer.parseInt(props.getProperty("backend.server.thread_count", "-1"));

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(nthreads == -1 ? new NioEventLoopGroup() : new NioEventLoopGroup(nthreads))
            .handler(new BackendConnectorIntializer()).channel(NioSocketChannel.class);
    try {//from  ww  w  .ja  v  a 2 s.c  om
        for (String s : backends) {
            URI uri = new URI("my://" + s);
            if (uri.getHost() == null || uri.getPort() == -1)
                throw new URISyntaxException(s, "Both host and port must be specified for host");
            LOG.debug("Connecting to: " + uri.getHost() + ":" + uri.getPort());

            ChannelFuture cf = bootstrap.connect(uri.getHost(), uri.getPort()).sync();
            if (cf.isSuccess())
                this.backends.put(s, cf.channel());
            else
                throw new IOException("Could not connect to backend " + s + ":" + uri.getPort());

        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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(/* w  ww.  j a  v a  2 s. c o  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()));
        }
    });
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyBackendHandler.java

License:Apache License

private void forward(final ChannelHandlerContext ctx, ByteBuf byteBuf) {
    if (inboundChannel.isActive()) {
        inboundChannel.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }/*from  w  w  w .  j  a  v a2  s . c o  m*/
            }
        });
    } else {
    }
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyBackendHandler.java

License:Apache License

private void handleSettingFrame(final ChannelHandlerContext ctx, Http2Flags flags) {
    ByteBufAllocator alloc = ctx.alloc();
    ByteBuf byteBuf = alloc.buffer();/*from w w  w . j  ava  2s .c o m*/
    if (!flags.ack()) {

        //00 00 0c 04 00 00 00 00 00 00 03 7f ff ff ff 00
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x0c);
        byteBuf.writeByte(0x04);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x03);
        byteBuf.writeByte(0x7f);
        byteBuf.writeByte(0xff);
        byteBuf.writeByte(0xff);
        byteBuf.writeByte(0xff);
        byteBuf.writeByte(0x00);
        //04 00 10 00 00
        byteBuf.writeByte(0x04);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x10);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
    } else {
        //            System.out.println("********************* setting ack received ...");
        //00 00 00 04 01 00 00 00 00
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x04);
        byteBuf.writeByte(0x01);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
    }
    ctx.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                //                    System.out.println(" ...operationComplete isSuccess");
                ctx.channel().read();
            } else {
                //                    System.out.println("...operationComplete failure");
                future.channel().close();
            }
        }
    });
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyBackendHandler.java

License:Apache License

private void handleWindowsUpdateFrame(final ChannelHandlerContext ctx) {
    ByteBufAllocator alloc = ctx.alloc();
    ByteBuf byteBuf = alloc.buffer();/*from w  w  w  .j a  v  a2s  . c om*/
    // 00 00 04 08 00 00 00 00 00 00 0f 00 01
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x04);
    byteBuf.writeByte(0x08);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x0f);
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(0x01);
    ctx.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                future.channel().close();
            }
        }
    });
}