Example usage for io.netty.channel ChannelFuture channel

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

Introduction

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

Prototype

Channel channel();

Source Link

Document

Returns a channel where the I/O operation associated with this future takes place.

Usage

From source file:com.tesora.dve.tools.libmy.AsyncExample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    final String mysqlHost = "localhost";
    final int mysqlPort = 3307;
    final String username = "root";
    final String password = "password";
    final boolean isClearText = true;

    final InetSocketAddress serverAddress = new InetSocketAddress(mysqlHost, mysqlPort);

    final MyBackendDecoder.CharsetDecodeHelper charsetHelper = constructCharsetDecodeHelper();
    final SimpleCredentials cred = constructCredentials(username, password, isClearText);
    final JavaCharsetCatalog javaCharsetCatalog = constructJavaCharsetCatalog();
    final MysqlClientAuthenticationHandler authHandler = new MysqlClientAuthenticationHandler(cred,
            ClientCapabilities.DEFAULT_PSITE_CAPABILITIES, javaCharsetCatalog, new AtomicReference<Charset>());

    final NioEventLoopGroup connectionEventGroup = new NioEventLoopGroup(1);
    final Bootstrap mysqlBootstrap = new Bootstrap();
    mysqlBootstrap // .group(inboundChannel.eventLoop())
            .channel(NioSocketChannel.class).group(connectionEventGroup)
            .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<Channel>() {
                @Override/* w ww  . ja v a  2 s  .  c om*/
                protected void initChannel(Channel ch) throws Exception {

                    ch.pipeline().addLast(authHandler).addLast(MyBackendDecoder.class.getSimpleName(),
                            new MyBackendDecoder(charsetHelper)).addLast(new ChannelDuplexHandler() {

                                @Override
                                public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                        throws Exception {
                                    System.out.println("WRITE:" + msg);
                                    super.write(ctx, msg, promise);
                                }

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg)
                                        throws Exception {
                                    if (msg instanceof MyFieldPktResponse) {
                                        final MyFieldPktResponse myFieldPktResponse = (MyFieldPktResponse) msg;
                                        System.out.println("COLUMN: " + myFieldPktResponse.getOrig_column()
                                                + "," + myFieldPktResponse.getColumn_type());
                                    } else if (msg instanceof MyTextResultRow) {
                                        final StringBuilder builder = new StringBuilder();
                                        builder.append("ROW:");
                                        final MyTextResultRow textRow = (MyTextResultRow) msg;
                                        for (int i = 0; i < textRow.size(); i++) {
                                            builder.append('\t');
                                            builder.append(textRow.getString(i));
                                        }
                                        System.out.println(builder.toString());
                                    }
                                    super.channelRead(ctx, msg);
                                }

                                @Override
                                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                    super.channelInactive(ctx);
                                    System.out.println("CLOSE. ");
                                }
                            });
                }
            });

    final ChannelFuture connectFut = mysqlBootstrap.connect(serverAddress);
    connectFut.sync();
    System.out.println("Waiting to finish authenticate handshake");

    authHandler.assertAuthenticated();//don't write a request until you know the login is complete.

    System.out.println("Connected, and authenticated, getting channel to write requests");

    final Channel chan = connectFut.channel();

    System.out.println("Sending two pipelined requests without blocking for first response.");

    chan.write(MSPComQueryRequestMessage.newMessage("show databases", CharsetUtil.UTF_8));
    chan.write(
            MSPComQueryRequestMessage.newMessage("select * from information_schema.tables", CharsetUtil.UTF_8));
    chan.flush();//NOTE:  nothing is sent until this is called.  Use writeAndFlush if you want it to go out immediately.

    System.out.println("Sleeping 5 sec so all results come back"); //normally you would sync to responses here.
    TimeUnit.SECONDS.sleep(5);
    System.out.println("Closing socket.");
    chan.writeAndFlush(MSPComQuitRequestMessage.newMessage());//send friendly hangup message. Probably correct to also wait for server close or an OK packet.

    chan.close();
    chan.closeFuture().sync();
    System.out.println("Exiting.");
    System.exit(0);
}

From source file:com.test.AbstractBootstrap.java

License:Apache License

private ChannelFuture doBind(final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }//from   w  w  w.jav  a 2s.com

    if (regFuture.isDone()) {
        // At this point we know that the registration was complete and successful.
        ChannelPromise promise = channel.newPromise();
        doBind0(regFuture, channel, localAddress, promise);
        return promise;
    } else {
        // Registration future is almost always fulfilled already, but just in case it's not.
        final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
        regFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Throwable cause = future.cause();
                if (cause != null) {
                    // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
                    // IllegalStateException once we try to access the EventLoop of the Channel.
                    promise.setFailure(cause);
                } else {
                    // Registration was successful, so set the correct executor to use.
                    // See https://github.com/netty/netty/issues/2586
                    promise.executor = channel.eventLoop();
                }
                doBind0(regFuture, channel, localAddress, promise);
            }
        });
        return promise;
    }
}

From source file:com.test.zp.netty.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    //        final SslContext sslCtx;
    //        if (SSL) {
    //            sslCtx = SslContextBuilder.forClient()
    //                .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    //        } else {
    //            sslCtx = null;
    //        }/*from   w  ww.  ja va  2  s .  c  o m*/

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //                     if (sslCtx != null) {
                        //                         p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        //                     }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.test.zp.netty.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    //        final SslContext sslCtx;
    //        if (SSL) {
    //            SelfSignedCertificate ssc = new SelfSignedCertificate();
    //            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    //        } else {
    //            sslCtx = null;
    //        }//from www .j  av  a  2  s .c o  m

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //                     if (sslCtx != null) {
                        //                         p.addLast(sslCtx.newHandler(ch.alloc()));
                        //                     }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.thomas.netty4.SimpleEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("PORT");
    if (args.length > 0) {
        PORT = Integer.parseInt(args[0]);
    }/* ww w. j av  a  2s .  co  m*/

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                // .option(ChannelOption.SO_BACKLOG, 100)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new SimpleEchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*www .jav  a  2  s. c o  m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnectManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecutor.start();
    }

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRpcServer.this.scanResponseTable();
            } catch (Exception e) {
                LOGGER.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    LOGGER.info("Rpc server [port:{}] start success", port);
}

From source file:com.topsec.bdc.platform.api.test.discard.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {// w w  w .j  a  va2 s  .c  o m
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(new DiscardClientHandler());
            }
        });

        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.topsec.bdc.platform.api.test.discard.DiscardServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*w  w  w.  j  a  va  2  s . c o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) {

                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new DiscardServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.topsec.bdc.platform.api.test.echo.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//  ww  w  .j  av  a2 s  .  c o m
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.topsec.bdc.platform.api.test.echo.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//  ww  w . jav a 2  s. c o  m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}