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:c5db.regionserver.RegionServerService.java

License:Apache License

@Override
protected void doStart() {
    fiber.start();/*w w w  . j a va 2s.c o  m*/

    fiber.execute(() -> {
        // we need the tablet module:
        ListenableFuture<C5Module> f = server.getModule(ModuleType.Tablet);
        Futures.addCallback(f, new FutureCallback<C5Module>() {
            @Override
            public void onSuccess(final C5Module result) {
                tabletModule = (TabletModule) result;
                bootstrap.group(acceptGroup, workerGroup).option(ChannelOption.SO_REUSEADDR, true)
                        .childOption(ChannelOption.TCP_NODELAY, true).channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast("http-server-codec", new HttpServerCodec());
                                p.addLast("http-agg",
                                        new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("websocket-agg",
                                        new WebSocketFrameAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("decoder", new WebsocketProtostuffDecoder("/websocket"));
                                p.addLast("encoder", new WebsocketProtostuffEncoder());
                                p.addLast("handler", new RegionServerHandler(RegionServerService.this));
                            }
                        });

                bootstrap.bind(port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            listenChannel = future.channel();
                            notifyStarted();
                        } else {
                            LOG.error("Unable to find Region Server to {} {}", port, future.cause());
                            notifyFailed(future.cause());
                        }
                    }
                });
            }

            @Override
            public void onFailure(Throwable t) {
                notifyFailed(t);
            }
        }, fiber);
    });
}

From source file:c5db.replication.ReplicatorService.java

License:Apache License

@FiberOnly
private void handleOutgoingMessage(final Request<RpcRequest, RpcWireReply> message) {
    final RpcRequest request = message.getRequest();
    final long to = request.to;

    if (to == nodeId) {
        handleLoopBackMessage(message);//from  w w  w.j  a  v a 2  s. c  om
        return;
    }

    // check to see if we have a connection:
    Channel channel = connections.get(to);
    if (channel != null && channel.isOpen()) {
        sendMessageAsync(message, channel);
        return;
    } else if (channel != null) {
        // stale?
        LOG.debug("Removing stale !isOpen channel from connections.get() for peer {}", to);
        connections.remove(to);
    }

    NodeInfoRequest nodeInfoRequest = new NodeInfoRequest(to, ModuleType.Replication);
    LOG.debug("node {} sending node info request {} ", nodeId, nodeInfoRequest);
    AsyncRequest.withOneReply(fiber, discoveryModule.getNodeInfo(), nodeInfoRequest,
            new Callback<NodeInfoReply>() {
                @SuppressWarnings("RedundantCast")
                @FiberOnly
                @Override
                public void onMessage(NodeInfoReply nodeInfoReply) {
                    if (!nodeInfoReply.found) {
                        LOG.debug("Can't find the info for the peer {}", to);
                        // TODO signal TCP/transport layer failure in a better way
                        //message.reply(null);
                        return;
                    }

                    LOG.debug("node {} got node info for node {} reply {} ", nodeId, to, nodeInfoReply);
                    // what if existing outgoing connection attempt?
                    Channel channel = connections.get(to);
                    if (channel != null && channel.isOpen()) {
                        sendMessageAsync(message, channel);
                        return;
                    } else if (channel != null) {
                        LOG.debug("Removing stale2 !isOpen channel from connections.get() for peer {}", to);
                        connections.remove(to);
                    }

                    // ok so we connect now:
                    ChannelFuture channelFuture = outgoingBootstrap.connect(nodeInfoReply.addresses.get(0),
                            nodeInfoReply.port);
                    LOG.trace("Connecting to peer {} at address {} port {}", to, nodeInfoReply.addresses.get(0),
                            nodeInfoReply.port);

                    // the channel might not be open, so defer the write.
                    connections.put(to, channelFuture.channel());
                    channelFuture.channel().closeFuture()
                            .addListener((ChannelFutureListener) future -> fiber.execute(() -> {
                                // remove only THIS channel. It might have been removed prior so.
                                connections.remove(to, future.channel());
                            }));

                    // funny hack, if the channel future is already open, we execute immediately!
                    channelFuture.addListener((ChannelFutureListener) future -> {
                        if (future.isSuccess()) {
                            sendMessageAsync(message, future.channel());
                        }
                    });
                }
            },
            // If the NodeInfoRequest times out:
            ReplicatorConstants.REPLICATOR_NODE_INFO_REQUEST_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS,
            () -> LOG.warn("node info request timeout {} ", nodeInfoRequest));
}

From source file:cat.tbq.hospital.nio.echoExample.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//from  w  w  w  .java  2s.  co 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());
                        //                            p.addLast(new EchoClient2Handler());
                    }
                });

        // 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:cat.tbq.hospital.nio.echoExample.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*w ww. j  a  v 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();
    }
}

From source file:cc.agentx.client.net.nio.XClient.java

License:Apache License

public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {/*from w  ww . ja v  a 2s  . co  m*/
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new SocksInitRequestDecoder()).addLast(new SocksMessageEncoder())
                                .addLast(new Socks5Handler()).addLast(Status.TRAFFIC_HANDLER);
                    }
                });
        log.info("\tStartup {}-{}-client [{}{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getMode(),
                config.getMode().equals("socks5") ? "" : ":" + config.getProtocol());
        ChannelFuture future = bootstrap.bind(config.getLocalHost(), config.getLocalPort()).sync();
        future.addListener(
                future1 -> log.info("\tListening at {}:{}...", config.getLocalHost(), config.getLocalPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:cc.agentx.server.net.nio.XServer.java

License:Apache License

public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  w  w  w . j  a v  a2 s .  c  o  m
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new XConnectHandler());
                        if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) {
                            socketChannel.pipeline().addLast(
                                    new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1),
                                            config.getWriteLimit(), config.getReadLimit()));
                        }
                    }
                });
        log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION,
                config.getProtocol());
        ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync();
        future.addListener(future1 -> log.info("\tListening at {}:{}...", config.getHost(), config.getPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down and recycling...");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        Configuration.shutdownRelays();
    }
    System.exit(0);
}

From source file:cc.sharper.netty.delimiter.EchoClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//from  w  w  w. j ava2 s. c o  m
    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 {
                        //? 
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));

                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

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

From source file:cc.sharper.netty.TimeClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//from w w  w . ja  v  a2 s .  c o  m
    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 {
                        ch.pipeline().addLast(new TimeClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

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

From source file:cc.sharper.netty.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO SocketChannel
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// w ww  .  j a  v a2  s .c  om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());//io
        // ???
        ChannelFuture f = b.bind(port).sync();

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

From source file:ch.ethz.globis.distindex.middleware.net.IndexMiddleware.java

License:Open Source License

@Override
public void run() {

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    balancingDaemon.run();/*  w  w  w  .  j a v  a  2s . c  o m*/
    try {
        //initialize the server channels
        ServerBootstrap b = initServerBootstrap(handler);
        ChannelFuture f = b.bind(port).sync();

        //register as a viable host to the cluster service
        clusterService.connect();
        if (joinedAsFree) {
            clusterService.registerFreeHost(getHostId());
        } else {
            clusterService.registerHost(getHostId());
        }
        isRunning = true;

        f.channel().closeFuture().sync();
    } catch (InterruptedException ie) {
        LOG.error("An error occurred while operating on the channel.", ie);
        ie.printStackTrace();
    } finally {
        closeEventLoops();
        isRunning = false;
        //disconnect the cluster service
        clusterService.disconnect();
    }
}