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:alluxio.network.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits for a response.
 *
 * @param context the netty RPC context//from   w  ww .  ja  va2s .c om
 * @param request the RPC request
 * @return the RPC response
 */
public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    final Promise<ProtoMessage> promise = channel.eventLoop().newPromise();
    channel.pipeline().addLast(new RPCHandler(promise));
    channel.writeAndFlush(new RPCProtoMessage(request)).addListener((ChannelFuture future) -> {
        if (future.cause() != null) {
            future.channel().close();
            promise.tryFailure(future.cause());
        }
    });
    ProtoMessage message;
    try {
        message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException | TimeoutException e) {
        CommonUtils.closeChannel(channel);
        throw new IOException(e);
    } catch (InterruptedException e) {
        CommonUtils.closeChannel(channel);
        throw new RuntimeException(e);
    } finally {
        if (channel.isOpen()) {
            channel.pipeline().removeLast();
        }
    }
    if (message.isResponse()) {
        CommonUtils.unwrapResponseFrom(message.asResponse(), context.getChannel());
    }
    return message;
}

From source file:alluxio.network.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits until the request is flushed to network. The caller of this method
 * should expect no response from the server and hence the service handler on server side should
 * not return any response or there will be issues. This method is typically used for RPCs
 * providing best efforts (e.g., async cache).
 *
 * @param context the netty RPC context/*from   w  w w. j a  v a2 s .com*/
 * @param request the RPC request
 */
public static void fireAndForget(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    // Not really using the atomicity of flushed, but use it as a wrapper of boolean that is final,
    // and can change value.
    final AtomicBoolean flushed = new AtomicBoolean(false);
    channel.writeAndFlush(new RPCProtoMessage(request)).addListener((ChannelFuture future) -> {
        if (future.cause() != null) {
            future.channel().close();
        }
        flushed.set(true);
        synchronized (flushed) {
            flushed.notify();
        }
    });
    try {
        synchronized (flushed) {
            while (!flushed.get()) {
                flushed.wait();
            }
        }
    } catch (InterruptedException e) {
        CommonUtils.closeChannel(channel);
        throw new RuntimeException(e);
    }
}

From source file:alluxio.network.protocol.RPCMessageIntegrationTest.java

License:Apache License

@BeforeClass
public static void beforeClass() {
    sEventClient = new NioEventLoopGroup(1);
    sEventServer = new NioEventLoopGroup(1);
    sIncomingHandler = new MessageSavingHandler();

    // Setup the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(sEventServer);/*w w w .j  av a2s  .  c  o m*/
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new PipelineInitializer(sIncomingHandler));

    InetSocketAddress address = new InetSocketAddress(NetworkAddressUtils.getLocalHostName(100),
            Constants.DEFAULT_MASTER_PORT);
    ChannelFuture cf = bootstrap.bind(address).syncUninterruptibly();
    sLocalAddress = cf.channel().localAddress();

    // Setup the client.
    sBootstrapClient = new Bootstrap();
    sBootstrapClient.group(sEventClient);
    sBootstrapClient.channel(NioSocketChannel.class);
    sBootstrapClient.handler(new PipelineInitializer(new MessageSavingHandler()));
}

From source file:alluxio.network.protocol.RPCMessageIntegrationTest.java

License:Apache License

@Before
public final void before() {
    sIncomingHandler.reset();/* w w w.j  av  a2  s . c  o m*/

    // Connect to the server.
    ChannelFuture cf = sBootstrapClient.connect(sLocalAddress).syncUninterruptibly();
    mOutgoingChannel = cf.channel();
}

From source file:alluxio.worker.netty.NettyDataServerTest.java

License:Apache License

private RPCResponse request(RPCRequest rpcBlockWriteRequest) throws Exception {
    InetSocketAddress address = new InetSocketAddress(mNettyDataServer.getBindHost(),
            mNettyDataServer.getPort());
    ClientHandler handler = new ClientHandler();
    Bootstrap clientBootstrap = NettyClient.createClientBootstrap(handler);
    ChannelFuture f = clientBootstrap.connect(address).sync();
    Channel channel = f.channel();
    try {/*from   w w  w.j a  va 2s.c  o m*/
        SingleResponseListener listener = new SingleResponseListener();
        handler.addListener(listener);
        channel.writeAndFlush(rpcBlockWriteRequest);
        return listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);
    } finally {
        channel.close().sync();
    }
}

From source file:basic.TimeClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO// w w w .j a  v  a  2  s  .  co  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:basic.TimeServer.java

License:Apache License

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

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

From source file:be.yildizgames.module.network.netty.client.ClientNetty.java

License:MIT License

@Override
public void connectImpl(final String address, final int port) {
    LOGGER.info("Connecting to server {}:{}", address, port);
    ChannelFuture future = this.bootstrap.connect(new InetSocketAddress(address, port));
    if (!future.awaitUninterruptibly().isSuccess()) {
        this.connectionFailed();
        this.bootstrap.config().group().shutdownGracefully();
    } else {/*  www  .java  2 s .  c o  m*/
        this.channel = future.channel();
        this.connectionComplete();
    }
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

/**
 * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture.
 * sessionClientToReplica is replaced with the new connection. Removed redundant
 * code./*from  w  w  w. j  a va2  s.  c  om*/
 */
public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {

    String str = this.clientId + ":" + replicaId;
    PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray());
    SecretKey authKey = fac.generateSecret(spec);

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec);
    b.handler(getChannelInitializer());

    ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId));

    NettyClientServerSession ncss = new NettyClientServerSession(channelFuture.channel(), replicaId);
    sessionClientToReplica.put(replicaId, ncss);

    return channelFuture;
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) {
    try {/*from ww w . j  a v  a 2s  .c om*/

        this.controller = controller;
        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        sessionReplicaToClient = new ConcurrentHashMap<>();
        rl = new ReentrantReadWriteLock();

        // Configure the server.

        serverPipelineFactory = new NettyServerPipelineFactory(this, sessionReplicaToClient, controller, rl);

        EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreads);
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, tcpSendBufferSize)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec)
                .option(ChannelOption.SO_BACKLOG, connectionBacklog)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(serverPipelineFactory.getDecoder());
                        ch.pipeline().addLast(serverPipelineFactory.getEncoder());
                        ch.pipeline().addLast(serverPipelineFactory.getHandler());
                    }
                }).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true);
        String myAddress;
        String confAddress = controller.getStaticConf()
                .getRemoteAddress(controller.getStaticConf().getProcessId()).getAddress().getHostAddress();

        if (InetAddress.getLoopbackAddress().getHostAddress().equals(confAddress)) {

            myAddress = InetAddress.getLoopbackAddress().getHostAddress();

        }

        else if (controller.getStaticConf().getBindAddress().equals("")) {

            myAddress = InetAddress.getLocalHost().getHostAddress();

            // If Netty binds to the loopback address, clients will not be able to connect
            // to replicas.
            // To solve that issue, we bind to the address supplied in config/hosts.config
            // instead.
            if (InetAddress.getLoopbackAddress().getHostAddress().equals(myAddress)
                    && !myAddress.equals(confAddress)) {

                myAddress = confAddress;
            }

        } else {

            myAddress = controller.getStaticConf().getBindAddress();
        }

        int myPort = controller.getStaticConf().getPort(controller.getStaticConf().getProcessId());

        ChannelFuture f = b.bind(new InetSocketAddress(myAddress, myPort)).sync();

        logger.info("ID = " + controller.getStaticConf().getProcessId());
        logger.info("N = " + controller.getCurrentViewN());
        logger.info("F = " + controller.getCurrentViewF());
        logger.info("Port (client <-> server) = "
                + controller.getStaticConf().getPort(controller.getStaticConf().getProcessId()));
        logger.info("Port (server <-> server) = "
                + controller.getStaticConf().getServerToServerPort(controller.getStaticConf().getProcessId()));
        logger.info("requestTimeout = " + controller.getStaticConf().getRequestTimeout());
        logger.info("maxBatch = " + controller.getStaticConf().getMaxBatchSize());
        if (controller.getStaticConf().getUseSignatures() == 1)
            logger.info("Using Signatures");
        else if (controller.getStaticConf().getUseSignatures() == 2)
            logger.info("Using benchmark signature verification");
        logger.info("Binded replica to IP address " + myAddress);
        // ******* EDUARDO END **************//

        /* Tulio Ribeiro */
        // SSL/TLS
        logger.info("SSL/TLS enabled, protocol version: {}",
                controller.getStaticConf().getSSLTLSProtocolVersion());

        /* Tulio Ribeiro END */

        mainChannel = f.channel();

    } catch (InterruptedException | UnknownHostException ex) {
        logger.error("Failed to create Netty communication system", ex);
    }
}