Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

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

Introduction

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

Prototype

ChannelFutureListener

Source Link

Usage

From source file:org.columbia.parikshan.proxy.NettyProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt to SERVER 2
    Bootstrap server2Bootstrap = new Bootstrap();
    server2Bootstrap.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new NettyProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture server2Future = server2Bootstrap.connect(remoteHost, remotePort);

    server2OutboundChannel = server2Future.channel();
    server2Future.addListener(new ChannelFutureListener() {
        @Override/*from  w  ww  .j av  a2s . c o m*/
        public void operationComplete(ChannelFuture future) {
            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:org.columbia.parikshan.proxy.NettyProxyFrontendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {

    if (server2OutboundChannel.isActive()) {
        if (server2OutboundChannel.isWritable()) {
            server2OutboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
                @Override//from w w  w. j  a v a 2  s  .  c  om
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) {
                        // was able to flush out data, start to read the next chunk
                        //System.out.println(counter++ +" Bytes Before UnWritable->" + server2OutboundChannel.bytesBeforeUnwritable());
                        ctx.channel().read();
                    } else {
                        future.channel().close();
                    }
                }
            });
        } else {
            System.out.println("Channel is no longer writeable");
            System.out.println(server2OutboundChannel.bytesBeforeUnwritable());
            System.out.println(server2OutboundChannel.bytesBeforeWritable());
        }
    }
}

From source file:org.dcache.xrootd.protocol.messages.AsyncResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) {
    try {/* w w w . ja  v  a 2  s.  c  o m*/
        int dlen = getDataLength();
        ByteBuf header = ctx.alloc().buffer(8 + dlen);
        try {
            header.writeShort(0);
            header.writeShort(kXR_attn);
            header.writeInt(dlen);
            header.writeInt(kXR_asynresp);
            header.writeInt(0);
        } catch (Error | RuntimeException t) {
            promise.setFailure(t);
            header.release();
            return;
        }
        ctx.write(header).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    promise.tryFailure(future.cause());
                }
            }
        });

        ChannelPromise channelPromise = ctx.newPromise();
        channelPromise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    promise.trySuccess();
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        });
        ReferenceCountUtil.retain(response).writeTo(ctx, channelPromise);
    } finally {
        release();
    }
}

From source file:org.dcache.xrootd.protocol.messages.ZeroCopyReadResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) {
    ByteBuf header = ctx.alloc().buffer(8);
    header.writeShort(request.getStreamId());
    header.writeShort(kXR_ok);/*from  w w w  . ja  va2  s  .  c o m*/
    header.writeInt(count);
    ctx.write(header).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
            }
        }
    });
    ctx.write(new DefaultFileRegion(file, request.getReadOffset(), count))
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        promise.trySuccess();
                    } else {
                        promise.tryFailure(future.cause());
                    }
                }
            });
}

From source file:org.dcache.xrootd.stream.ChunkedResponseWriteHandler.java

License:Open Source License

private boolean doFlush(final ChannelHandlerContext ctx) throws Exception {
    final Channel channel = ctx.channel();
    if (!channel.isActive()) {
        discard(null);/*from w  ww .  ja va  2  s  . c o  m*/
        return false;
    }
    boolean flushed = false;
    while (channel.isWritable()) {
        if (currentWrite == null) {
            currentWrite = queue.poll();
        }

        if (currentWrite == null) {
            break;
        }
        final PendingWrite currentWrite = this.currentWrite;
        final ChunkedResponse pendingMessage = currentWrite.msg;

        boolean endOfInput;
        Object message = null;
        try {
            message = pendingMessage.nextChunk(ctx.alloc());
            endOfInput = pendingMessage.isEndOfInput();
        } catch (final Throwable t) {
            this.currentWrite = null;

            if (message != null) {
                ReferenceCountUtil.release(message);
            }

            currentWrite.fail(t);
            break;
        }

        if (message == null) {
            // If message is null write an empty ByteBuf.
            // See https://github.com/netty/netty/issues/1671
            message = Unpooled.EMPTY_BUFFER;
        }

        final int amount = amount(message);
        ChannelFuture f = ctx.write(message);
        if (endOfInput) {
            this.currentWrite = null;

            // Register a listener which will close the input once the write is complete.
            // This is needed because the Chunk may have some resource bound that can not
            // be closed before its not written.
            //
            // See https://github.com/netty/netty/issues/303
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        currentWrite.fail(future.cause());
                    } else {
                        currentWrite.progress(amount);
                        currentWrite.success();
                    }
                }
            });
        } else {
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        currentWrite.fail(future.cause());
                    } else {
                        currentWrite.progress(amount);
                    }
                }
            });
        }

        // Always need to flush
        ctx.flush();
        flushed = true;

        if (!channel.isActive()) {
            discard(new ClosedChannelException());
            break;
        }
    }
    return flushed;

}

From source file:org.eclipse.milo.opcua.stack.server.tcp.SocketServer.java

License:Open Source License

public synchronized void bind() throws ExecutionException, InterruptedException {
    if (channel != null)
        return; // Already bound

    CompletableFuture<Unit> bindFuture = new CompletableFuture<>();

    bootstrap.bind(address).addListener(new ChannelFutureListener() {
        @Override//from   ww  w . j av  a 2  s  .  c  o m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                bindFuture.complete(Unit.VALUE);
            } else {
                bindFuture.completeExceptionally(future.cause());
            }
        }
    });

    bindFuture.get();
}

From source file:org.enderstone.server.packet.NetworkManager.java

License:Open Source License

/**
 * Disconnects the player//from w  ww .j a v a  2s  .c o m
 *
 * @param message
 *            the message to kick the player
 * @param byError
 *            if true, then the reason of the kick is printed in the console
 */
public void disconnect(Message message, boolean byError) {
    try {
        this.ctx.channel().pipeline().addFirst("packet_r_disconnected", new DiscardingReader());
        Level level = byError ? Level.WARNING : Level.INFO;
        if (this.player == null)
            EnderLogger.logger.log(level,
                    "Kicking unregistered channel " + this.digitalName() + ": " + message.toPlainText());
        else
            EnderLogger.logger.log(level, "Kicking " + this.digitalName() + ": " + message.toPlainText());
        Packet p = codex.getDisconnectionPacket(message);
        if (p != null) {
            synchronized (packets) {
                ChannelFuture f = ctx.write(p);
                f.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) {
                        ctx.close();
                    }
                });
                ctx.flush();
            } // ChannelFutureListener.CLOSE
        } else
            ctx.close();
    } catch (Exception ex) {
        EnderLogger.exception(ex);
    } finally {
        this.disconnectConnection();
    }
}

From source file:org.fiware.kiara.netty.BaseHandler.java

License:Open Source License

protected final void closeChannel() {
    if (channel != null) {
        channel.closeFuture().addListener(new ChannelFutureListener() {

            public void operationComplete(ChannelFuture future) throws Exception {
                future.removeListener(this);
                state = State.CLOSED;
                channel = null;/*from   w w w . ja v  a2 s.  c om*/
            }

        });
    }
}

From source file:org.fusesource.hawtdispatch.netty.HawtServerSocketChannel.java

License:Apache License

@Override
protected Runnable doRegister() throws Exception {
    final Runnable task = super.doRegister();

    return new Runnable() {
        @Override//www.ja v a2 s  .c  o m
        public void run() {
            if (task != null) {
                task.run();
            }
            // Create the source and register the handlers to it
            acceptSource = createSource(OP_ACCEPT);
            acceptSource.setEventHandler(new Task() {
                @Override
                public void run() {
                    boolean added = false;
                    for (;;) {
                        try {
                            SocketChannel channel = javaChannel().accept();
                            if (channel == null) {
                                break;
                            }
                            pipeline().inboundMessageBuffer()
                                    .add(new HawtSocketChannel(HawtServerSocketChannel.this, null, channel));
                            added = true;

                        } catch (IOException e) {
                            if (isOpen()) {
                                logger.warn("Failed to create a new channel from an accepted socket.", e);
                            }
                            break;
                        }
                    }
                    if (added) {
                        pipeline().fireInboundBufferUpdated();
                        pipeline().fireChannelReadSuspended();
                    }

                    // suspend accepts if needed
                    if (!config().isAutoRead()) {
                        acceptSource.suspend();
                    }
                }
            });
            closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    acceptSource.cancel();
                }
            });
        }
    };

}

From source file:org.fusesource.hawtdispatch.netty.HawtSocketChannel.java

License:Apache License

@Override
protected Runnable doRegister() throws Exception {
    final Runnable task = super.doRegister();
    return new Runnable() {
        @Override/*from  w  ww  .  ja v  a  2  s .co  m*/
        public void run() {
            if (task != null) {
                task.run();
            }
            // create the sources and set the event handlers
            readSource = createSource(OP_READ);
            readSource.setEventHandler(new Task() {
                @Override
                public void run() {
                    onReadReady();
                }
            });
            writeSource = createSource(OP_WRITE);
            writeSource.setEventHandler(new Task() {
                @Override
                public void run() {
                    unsafe().flushNow();
                }
            });
            closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    readSource.cancel();
                    writeSource.cancel();
                }
            });
        }
    };
}