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:MultiThreadClient.java

License:Apache License

public void run() throws Exception {
    try {/* w w w . ja  va2  s.  c om*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelDuplexHandler() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println(
                                index + "-??:" + msg + "Read:" + Thread.currentThread());
                    }

                    @Override
                    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                            throws Exception {
                        ChannelFuture future = ctx.writeAndFlush(msg, promise);
                        System.out.println(index + "-Write:" + Thread.currentThread());
                        Thread.yield();
                        Thread.yield();
                        future.addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                System.out.println(index + "-Listener" + "Lintener:"
                                        + Thread.currentThread());
                            }
                        });
                    }
                });

        // Make the connection attempt.
        ChannelFuture f = b.connect(host, port).sync();
        for (int i = 0; i < 10; i++) {
            f.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[10]));
        }
        // Wait until the connection is closed.

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

From source file:NettyInboundHttpTargetHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    //   System.out.println("Receving data");
    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override// w w  w .ja v a 2s . c  o m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                future.channel().close();
            }
        }
    });
}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx/*from  ww w. j a v  a  2  s  .  c om*/
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * receiving events through netty./*from www. j a v a  2 s . c o m*/
 *
 * @param ctx
 * @param msg
 * @throws Exception
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    if (outboundChannel.isActive()) {
        outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // was able to flush out data, start to read the next chunk
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    } else {
        // System.out.println("Outbound Channel Not Active");
    }
}

From source file:alluxio.client.netty.NettyRemoteBlockReader.java

License:Apache License

@Override
public ByteBuffer readRemoteBlock(InetSocketAddress address, long blockId, long offset, long length,
        long lockId, long sessionId) throws IOException {
    SingleResponseListener listener = null;
    try {/* w ww .ja  va  2s . com*/
        ChannelFuture f = mClientBootstrap.connect(address).sync();

        LOG.info("Connected to remote machine {}", address);
        Channel channel = f.channel();
        listener = new SingleResponseListener();
        mHandler.addListener(listener);
        channel.writeAndFlush(new RPCBlockReadRequest(blockId, offset, length, lockId, sessionId));

        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);
        channel.close().sync();

        switch (response.getType()) {
        case RPC_BLOCK_READ_RESPONSE:
            RPCBlockReadResponse blockResponse = (RPCBlockReadResponse) response;
            LOG.info("Data {} from remote machine {} received", blockId, address);

            RPCResponse.Status status = blockResponse.getStatus();
            if (status == RPCResponse.Status.SUCCESS) {
                // always clear the previous response before reading another one
                close();
                mReadResponse = blockResponse;
                return blockResponse.getPayloadDataBuffer().getReadOnlyByteBuffer();
            }
            throw new IOException(status.getMessage() + " response: " + blockResponse);
        case RPC_ERROR_RESPONSE:
            RPCErrorResponse error = (RPCErrorResponse) response;
            throw new IOException(error.getStatus().getMessage());
        default:
            throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(),
                    RPCMessage.Type.RPC_BLOCK_READ_RESPONSE));
        }
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        if (listener != null) {
            mHandler.removeListener(listener);
        }
    }
}

From source file:alluxio.client.netty.NettyRemoteBlockWriter.java

License:Apache License

@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
    SingleResponseListener listener = null;
    try {//w w w .  j a v  a2  s  .  c o m
        // TODO(hy): keep connection open across multiple write calls.
        ChannelFuture f = mClientBootstrap.connect(mAddress).sync();

        LOG.info("Connected to remote machine {}", mAddress);
        Channel channel = f.channel();
        listener = new SingleResponseListener();
        mHandler.addListener(listener);
        channel.writeAndFlush(new RPCBlockWriteRequest(mSessionId, mBlockId, mWrittenBytes, length,
                new DataByteArrayChannel(bytes, offset, length)));

        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);
        channel.close().sync();

        switch (response.getType()) {
        case RPC_BLOCK_WRITE_RESPONSE:
            RPCBlockWriteResponse resp = (RPCBlockWriteResponse) response;
            RPCResponse.Status status = resp.getStatus();
            LOG.info("status: {} from remote machine {} received", status, mAddress);

            if (status != RPCResponse.Status.SUCCESS) {
                throw new IOException(ExceptionMessage.BLOCK_WRITE_ERROR.getMessage(mBlockId, mSessionId,
                        mAddress, status.getMessage()));
            }
            mWrittenBytes += length;
            break;
        case RPC_ERROR_RESPONSE:
            RPCErrorResponse error = (RPCErrorResponse) response;
            throw new IOException(error.getStatus().getMessage());
        default:
            throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(),
                    RPCMessage.Type.RPC_BLOCK_WRITE_RESPONSE));
        }
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        if (listener != null) {
            mHandler.removeListener(listener);
        }
    }
}

From source file:alluxio.client.netty.NettyUnderFileSystemFileReader.java

License:Apache License

/**
 * Reads data from the specified worker for a file in the under file system.
 *
 * @param address the worker address to read from
 * @param ufsFileId the worker specific file id referencing the file to read
 * @param offset the offset in the file to read from
 * @param length the length to read/*from  w w  w .java 2  s  .  c  o  m*/
 * @return a byte buffer with the requested data, null if EOF is reached
 * @throws IOException if an error occurs communicating with the worker
 */
public ByteBuffer read(InetSocketAddress address, long ufsFileId, long offset, long length) throws IOException {
    // For a zero length read, directly return without trying the Netty call.
    if (length == 0) {
        return ByteBuffer.allocate(0);
    }
    SingleResponseListener listener = null;
    try {
        ChannelFuture f = mClientBootstrap.connect(address).sync();

        LOG.debug("Connected to remote machine {}", address);
        Channel channel = f.channel();
        listener = new SingleResponseListener();
        mHandler.addListener(listener);
        channel.writeAndFlush(new RPCFileReadRequest(ufsFileId, offset, length));

        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);
        channel.close().sync();

        switch (response.getType()) {
        case RPC_FILE_READ_RESPONSE:
            RPCFileReadResponse resp = (RPCFileReadResponse) response;
            LOG.debug("Data for ufs file id {} from machine {} received", ufsFileId, address);
            RPCResponse.Status status = resp.getStatus();
            if (status == RPCResponse.Status.SUCCESS) {
                // always clear the previous response before reading another one
                cleanup();
                // End of file reached
                if (resp.isEOF()) {
                    return null;
                }
                mReadResponse = resp;
                return resp.getPayloadDataBuffer().getReadOnlyByteBuffer();
            }
            throw new IOException(status.getMessage() + " response: " + resp);
        case RPC_ERROR_RESPONSE:
            RPCErrorResponse error = (RPCErrorResponse) response;
            throw new IOException(error.getStatus().getMessage());
        default:
            throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(),
                    RPCMessage.Type.RPC_FILE_READ_RESPONSE));
        }
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        if (listener != null) {
            mHandler.removeListener(listener);
        }
    }
}

From source file:alluxio.client.netty.NettyUnderFileSystemFileWriter.java

License:Apache License

/**
 * Writes data to the file in the under file system.
 *
 * @param address worker address to write the data to
 * @param ufsFileId worker file id referencing the file
 * @param fileOffset where in the file to start writing, only sequential writes are supported
 * @param bytes data to write// w w w.ja  v a 2  s  . c  om
 * @param offset start offset of the data
 * @param length length to write
 * @throws IOException if an error occurs during the write
 */
public void write(InetSocketAddress address, long ufsFileId, long fileOffset, byte[] bytes, int offset,
        int length) throws IOException {
    SingleResponseListener listener = null;
    try {
        ChannelFuture f = mClientBootstrap.connect(address).sync();

        LOG.debug("Connected to remote machine {}", address);
        Channel channel = f.channel();
        listener = new SingleResponseListener();
        mHandler.addListener(listener);
        channel.writeAndFlush(new RPCFileWriteRequest(ufsFileId, fileOffset, length,
                new DataByteArrayChannel(bytes, offset, length)));

        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);
        channel.close().sync();

        switch (response.getType()) {
        case RPC_FILE_WRITE_RESPONSE:
            RPCFileWriteResponse resp = (RPCFileWriteResponse) response;
            RPCResponse.Status status = resp.getStatus();
            LOG.debug("status: {} from remote machine {} received", status, address);

            if (status != RPCResponse.Status.SUCCESS) {
                throw new IOException(ExceptionMessage.UNDER_FILE_WRITE_ERROR.getMessage(ufsFileId, address,
                        status.getMessage()));
            }
            break;
        case RPC_ERROR_RESPONSE:
            RPCErrorResponse error = (RPCErrorResponse) response;
            throw new IOException(error.getStatus().getMessage());
        default:
            throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(),
                    RPCMessage.Type.RPC_FILE_WRITE_RESPONSE));
        }
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        if (listener != null) {
            mHandler.removeListener(listener);
        }
    }
}

From source file:alluxio.network.connection.NettyChannelPool.java

License:Apache License

/**
 * Creates a netty channel instance./*w  w w .ja va  2s  .c  o m*/
 *
 * @return the channel created
 * @throws IOException if it fails to create a channel
 */
@Override
protected Channel createNewResource() throws IOException {
    Bootstrap bs;
    try {
        bs = mBootstrap.clone();
    } catch (Exception e) {
        // No exception should happen here.
        throw Throwables.propagate(e);
    }
    try {
        ChannelFuture channelFuture = bs.connect().sync();
        if (channelFuture.isSuccess()) {
            LOG.info("Created netty channel with netty bootstrap {}.", mBootstrap);
            return channelFuture.channel();
        } else {
            LOG.error("Failed to create netty channel with netty bootstrap {} and error {}.", mBootstrap,
                    channelFuture.cause().getMessage());
            throw new IOException(channelFuture.cause());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

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

License:Apache License

/**
 * Creates a netty channel instance.//w ww . j  a  va 2 s . c o m
 *
 * @return the channel created
 */
@Override
protected Channel createNewResource() throws IOException {
    Bootstrap bs;
    bs = mBootstrap.clone();
    try {
        ChannelFuture channelFuture = bs.connect().sync();
        if (channelFuture.isSuccess()) {
            LOG.info("Created netty channel with netty bootstrap {}.", mBootstrap);
            return channelFuture.channel();
        } else {
            LOG.error("Failed to create netty channel with netty bootstrap {} and error {}.", mBootstrap,
                    channelFuture.cause().getMessage());
            throw new UnavailableException(channelFuture.cause());
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CanceledException(e);
    }
}