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:de.dfki.kiara.http.HttpHandler.java

License:Open Source License

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

            @Override/*  ww w.  j a  v  a  2 s  . c o  m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                future.removeListener(this);
                state = State.CLOSED;
                channel = null;
            }

        });
    }
}

From source file:de.dfki.kiara.netty.ListenableConstantFutureAdapter.java

License:Open Source License

@Override
public void addListener(final Runnable r, final Executor exctr) {
    future.addListener(new ChannelFutureListener() {
        @Override/*w  w  w .j  a va  2s. co  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            exctr.execute(r);
        }
    });
}

From source file:de.jackwhite20.japs.shared.nio.NioSocketClient.java

License:Open Source License

public boolean connect(String host, int port) {

    ChannelFuture channelFuture = new Bootstrap().group(PipelineUtils.newEventLoopGroup(1))
            .channel(PipelineUtils.getChannel()).handler(new ClientChannelInitializer(this))
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT).connect(host, port);

    channelFuture.awaitUninterruptibly();

    channel = channelFuture.channel();/*w w w.  ja  va 2 s.  co  m*/

    CountDownLatch countDownLatch = new CountDownLatch(1);

    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            connected = channelFuture.isSuccess();

            countDownLatch.countDown();
        }
    });

    try {
        countDownLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return connected;
}

From source file:de.unipassau.isl.evs.ssh.core.network.Client.java

License:Open Source License

/**
 * Tries to establish a TCP connection to the Server with the given host and port.
 * If the connect ist successful, {@link #getHandshakeHandler()} is used to add the
 * required Handlers to the pipeline./*from   w  ww.j  av a  2s.  c o  m*/
 * If the connection fails, {@link #channelClosed(Channel)} is called until to many retries are made and the Client
 * switches to searching the master via UDP discovery using the {@link UDPDiscoveryClient}.
 */
private void connectClient(InetSocketAddress address) {
    Log.i(TAG, "Client connecting to " + address);
    notifyClientConnecting(address.getHostString(), address.getPort());

    // TCP Connection
    Bootstrap b = new Bootstrap().group(requireComponent(ExecutionServiceComponent.KEY))
            .channel(NioSocketChannel.class).handler(getHandshakeHandler())
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(5));

    // Wait for the start of the client
    channelFuture = b.connect(address);
    channelFuture.addListener(new ChannelFutureListener() {
        /**
         * Called once the operation completes, either because the connect was successful or because of an error.
         */
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                Log.v(TAG, "Channel open");
                channelOpen(future.channel());
            } else {
                Log.v(TAG, "Channel open failed");
                channelClosed(future.channel());
            }
        }
    });
    channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
        /**
         * Called once the connection is closed.
         */
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            Log.v(TAG, "Channel closed");
            channelClosed(future.channel());
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.master.activity.MasterMainActivity.java

License:Open Source License

@NonNull
private ChannelFutureListener newConnectionClosedListener(final String name) {
    return new ChannelFutureListener() {
        @Override/*from  ww w . j  av a  2 s. c o  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String text = String.format(getResources().getString(R.string.closed_connection_with),
                            name);
                    Toast.makeText(MasterMainActivity.this, text, Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
}

From source file:de.unipassau.isl.evs.ssh.master.network.ServerHandshakeHandler.java

License:Open Source License

protected void handshakeSuccessful(ChannelHandlerContext ctx) {
    final State state = getState(ctx);
    if (state != State.FINISHED) {
        throw new IllegalStateException("Handshake not finished: " + state);
    }/*  ww w .  ja va 2s.co  m*/
    final DeviceID deviceID = ctx.channel().attr(ATTR_PEER_ID).get();

    // allow pings
    TimeoutHandler.setPingEnabled(ctx.channel(), true);
    // add Dispatcher
    ctx.pipeline().addBefore(ctx.name(), IncomingDispatcher.class.getSimpleName(),
            container.require(IncomingDispatcher.KEY));
    // Logging is handled by IncomingDispatcher and OutgoingRouter
    ctx.pipeline().remove(LoggingHandler.class.getSimpleName());
    // remove HandshakeHandler
    ctx.pipeline().remove(this);

    // Register connection
    server.getActiveChannels().add(ctx.channel());
    Log.i(TAG, "Handshake with " + deviceID + " successful, current Pipeline: " + ctx.pipeline());

    Message message = new Message(
            new DeviceConnectedPayload(deviceID, ctx.channel(), ctx.attr(ATTR_LOCAL_CONNECTION).get()));
    container.require(OutgoingRouter.KEY).sendMessageLocal(RoutingKeys.MASTER_DEVICE_CONNECTED, message);

    ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            for (Server.ServerConnectionListener listener : server.listeners) {
                listener.onClientConnected(future.channel());
            }
        }
    });

    for (Server.ServerConnectionListener listener : server.listeners) {
        listener.onClientConnected(ctx.channel());
    }
}

From source file:deathcap.wsmc.web.WebSocketHandler.java

License:Apache License

@Override
protected void messageReceived(final ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception { // channelRead
    if (firstMessage) {
        firstMessage = false;/*from  w w  w. j  a v a2s .  com*/
        this.webThread.getChannelGroup().add(ctx.channel());
    }

    MinecraftThread minecraft = minecraftThreads.get(ctx.channel().remoteAddress().toString());
    if (minecraft == null) {
        this.setupInitialConnection(ctx, msg);
        return;
    }

    final ByteBuf buf = msg.content();

    if (verbose)
        logger.info("ws received " + buf.readableBytes() + " bytes: " + HexDumper.hexByteBuf(buf));

    byte bytes[] = new byte[buf.readableBytes()];
    buf.readBytes(bytes);

    // read packet id type for filtering
    int id = DefinedPacket.readVarInt(Unpooled.copiedBuffer(bytes)); // TODO: avoid copying (but need to reply with id in buffer)

    if (!this.filter.isAllowed(id)) {
        logger.info("FILTERED PACKET: " + id);
        return;
    }

    final ByteBuf reply = Unpooled.wrappedBuffer(bytes).retain();
    if (verbose)
        logger.info(
                "id " + id + " stripped " + reply.readableBytes() + " reply=" + HexDumper.hexByteBuf(reply));

    final MinecraftThread mc = minecraft;
    // forward MC to WS
    try {
        final ChannelFuture f = mc.clientHandler.minecraftClientHandler.ctx.writeAndFlush(reply);

        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                try {
                    assert f == channelFuture;
                    if (verbose)
                        logger.info("forwarded WS -> MC, " + reply.readableBytes() + " bytes");
                    reply.release();
                } catch (RejectedExecutionException ex) {
                    // TODO
                }
            }
        });
    } catch (RejectedExecutionException ex) {
        //TODO mc.clientHandler.minecraftClientHandler.close(ctx, )
    }

}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private void safeClose(final ChannelHandlerContext ctx, ChannelFuture flushFuture,
        final ChannelPromise promise) {
    if (!ctx.channel().isActive()) {
        ctx.close(promise);//  w w  w.  j a v a  2s .com
        return;
    }

    final ScheduledFuture<?> timeoutFuture;
    if (closeNotifyTimeoutMillis > 0) {
        // Force-close the connection if close_notify is not fully sent in time.
        timeoutFuture = ctx.executor().schedule(new Runnable() {
            @Override
            public void run() {
                logger.warn(
                        ctx.channel() + " last write attempt timed out." + " Force-closing the connection.");
                ctx.close(promise);
            }
        }, closeNotifyTimeoutMillis, TimeUnit.MILLISECONDS);
    } else {
        timeoutFuture = null;
    }

    // Close the connection if close_notify is sent in time.
    flushFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
            // Trigger the close in all cases to make sure the promise is notified
            // See https://github.com/netty/netty/issues/2358
            ctx.close(promise);
        }
    });
}

From source file:enetty.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        System.out.println("uri: " + req.uri());
    }//from   w ww  . j  a v a2s. co m
    if (outboundChannel.isActive()) {
        outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // was able to flush out data, start to read the next chunk
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    }
}

From source file:eu.heronnet.module.kad.net.ClientImpl.java

License:Open Source License

private void broadcastOnInterface(InterfaceAddress interfaceAddress, Messages.Request request) {
    InetAddress broadcast = interfaceAddress.getBroadcast();
    if (broadcast != null) {
        ByteString messageId = request.getMessageId();
        udpBoostrap.handler(new ResponseHandler(messageId.toByteArray()));
        udpBoostrap.bind(0).addListener(new ChannelFutureListener() {
            @Override/*from w  ww  .  j  a va 2 s. c  o m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    final Channel channel = future.channel();

                    final ByteBuf requestBuffer = Unpooled.wrappedBuffer(request.toByteArray());
                    final DatagramPacket datagramPacket = new DatagramPacket(requestBuffer,
                            new InetSocketAddress(broadcast, selfNodeProvider.getSelf().getPort()));
                    channel.writeAndFlush(datagramPacket);
                    channel.close();
                    logger.debug("completed operation: {}", future.toString());
                } else {
                    logger.error("Error in channel bootstrap: {}", future.cause().getMessage());
                }
            }
        });
    }
}