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:chapter01.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {//  ww w.  ja v  a2 s  .c o  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoClientHandler());
            }
        });

        ChannelFuture f = b.connect("localhost", 8888).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:chat.viska.xmpp.NettyTcpSession.java

License:Apache License

@SchedulerSupport(SchedulerSupport.CUSTOM)
@Override//ww w.  j av  a  2  s  .c  o  m
protected Completable openConnection(final Compression connectionCompression,
        final Compression tlsCompression) {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(nettyEventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel channel) throws SSLException {
            if (getConnection().getTlsMethod() == Connection.TlsMethod.DIRECT) {
                tlsHandler = TLS_CONTEXT_BUILDER.build().newHandler(channel.alloc());
                channel.pipeline().addLast(PIPE_TLS, tlsHandler);
            } else {
                channel.pipeline().addLast(PIPE_TLS, new ChannelDuplexHandler());
            }
            channel.pipeline().addLast(PIPE_COMPRESSOR, new ChannelDuplexHandler());
            channel.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_STANZA_SIZE_BYTE, false, false,
                    Unpooled.wrappedBuffer(">".getBytes(StandardCharsets.UTF_8))));
            channel.pipeline().addLast(new StreamClosingDetector());
            channel.pipeline().addLast(PIPE_DECODER_XML, new XmlDecoder());
            channel.pipeline().addLast(new SimpleChannelInboundHandler<XmlDocumentStart>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final XmlDocumentStart msg)
                        throws Exception {
                    if (!"UTF-8".equalsIgnoreCase(msg.encoding())) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.UNSUPPORTED_ENCODING,
                                "Only UTF-8 is supported in XMPP stream."));
                    }
                }
            });
            channel.pipeline().addLast(new StreamOpeningDetector());
            channel.pipeline().addLast(new XmlFrameDecoder(MAX_STANZA_SIZE_BYTE));
            channel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final String msg)
                        throws Exception {
                    try {
                        feedXmlPipeline(preprocessInboundXml(msg));
                    } catch (SAXException ex) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.BAD_FORMAT));
                    }
                }
            });
            channel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
                }

                @Override
                public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
                    if (cause instanceof Exception) {
                        triggerEvent(new ExceptionCaughtEvent(NettyTcpSession.this, (Exception) cause));
                    } else {
                        throw new RuntimeException(cause);
                    }
                }
            });
        }
    });

    final ChannelFuture channelFuture = bootstrap.connect(getConnection().getDomain(),
            getConnection().getPort());
    return Completable.fromFuture(channelFuture).andThen(Completable.fromAction(() -> {
        this.nettyChannel = (SocketChannel) channelFuture.channel();
        nettyChannel.closeFuture().addListener(it -> changeStateToDisconnected());
    }));
}

From source file:client.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//  ww w  . ja v a  2  s.  co m
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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:cloudeventbus.client.EventBusImpl.java

License:Open Source License

private void connect() {
    synchronized (lock) {
        if (closed) {
            return;
        }/*  www  .  j  a  v a 2 s.com*/
        serverReady = false;
    }
    final ServerList.Server server = servers.nextServer();
    LOGGER.debug("Attempting connecting to {}", server.getAddress());
    new Bootstrap().group(eventLoopGroup).remoteAddress(server.getAddress()).channel(NioSocketChannel.class)
            .handler(new ClientChannelInitializer()).connect().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        LOGGER.debug("Connection to {} successful", server.getAddress());
                        server.connectionSuccess();
                        synchronized (lock) {
                            channel = future.channel();
                            if (closed) {
                                channel.close();
                            }
                        }
                    } else {
                        LOGGER.warn("Connection to {} failed", server.getAddress());
                        server.connectionFailure();
                        scheduleReconnect();
                        fireStateChange(ConnectionState.CONNECTION_FAILED, null);
                    }
                }
            });
}

From source file:club.jmint.crossing.server.CrossingServer.java

License:Apache License

public void start() {
    //load configuration
    //ConfigWizard cw = (ConfigWizard)WizardManager.getWizard("ConfigWizard");
    ServerConfig config = (ServerConfig) ConfigWizard.getConfig(Constants.CONFIG_SERVER);
    this.address = config.getItem("server.bind_address");
    this.port = Integer.parseInt(config.getItem("server.port"));
    this.backlog = Integer.parseInt(config.getItem("server.backlog"));
    this.ssl = Boolean.parseBoolean(config.getItem("server.ssl"));

    //Configure SSL
    if (ssl) {//ww w. j a va2  s .  co  m
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } catch (Exception e) {
            CrossLog.printStackTrace(e);
        }
    } 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, backlog).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ServerChannelInitializer(sslCtx));

        // Start the server.
        ChannelFuture f = b.bind(port).sync();
        CrossLog.logger.info("Crossing Server started......");

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();

    } catch (InterruptedException e) {
        CrossLog.printStackTrace(e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        CrossLog.logger.info("Crossing Server shutdown......");
    }
}

From source file:cn.david.main.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  a 2s .com*/
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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:cn.david.main.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   w w w. j ava  2s  . c om
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } 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();
    }
}

From source file:cn.david.main.PersonServer.java

License:Apache License

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

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   ww w.  j  a va  2  s .  co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ServerInitializer());

        // 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:cn.dennishucd.nettyhttpserver.HttpServer.java

License:Apache License

public void start(String host, int port) throws Exception {
    //create a reactor thread pool for NIO acceptor
    EventLoopGroup bossGroup = new NioEventLoopGroup();

    //create a reactor thread pool for NIO handler
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from   w ww .ja  v a  2  s .  c o m*/
        ServerBootstrap b = new ServerBootstrap();

        b.option(ChannelOption.SO_BACKLOG, 1024);

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new PushServerInitializer());

        ChannelFuture f = b.bind(host, port).sync();

        logger.info("The http server is started on " + host + ":" + port);

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:cn.savor.small.netty.NettyClient.java

License:Open Source License

public void connect() {
    System.out.println("client connection.................");
    if (channel != null && channel.isActive()) {
        return;/*from w  w w  .j  a v a  2 s.  c  om*/
    }

    ChannelFuture future = bootstrap.connect(host, port);
    System.out.println("client connection.................host=" + host + ",port=" + port + ",future="
            + future.isSuccess());

    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture futureListener) throws Exception {
            if (futureListener.isSuccess()) {
                channel = futureListener.channel();
                System.out.println("Connect to server successfully!");
            } else {
                System.out.println("Failed to connect to server, try connect after 10s");

                futureListener.channel().eventLoop().schedule(new Runnable() {
                    @Override
                    public void run() {
                        connect();
                    }
                }, 1, TimeUnit.SECONDS);
            }
        }
    });
}