Example usage for io.netty.channel ChannelFuture addListener

List of usage examples for io.netty.channel ChannelFuture addListener

Introduction

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

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:de.felix_klauke.pegasus.server.handler.PacketHandler.java

License:Apache License

/**
 *
 *  The Method everything is about. All incoming data will be handled by this method.
 *  It will check all received data. When the object containing this data is an instance
 *  of {@link de.felix_klauke.pegasus.protocol.Packet}.
 *
 *  This is the Main Handler for Handshakes.
 *
 *  The other packets will be/*from w w w.  j  a v a2s  .co m*/
 *  passed to the method that will handle all incoming packets:
 *  {@link de.felix_klauke.pegasus.server.handler.PacketHandler#handlePacket(Channel, Packet)}
 *
 * @param ctx the context of the channel that received the data
 * @param msg the data the channel received
 * @throws Exception the exception that occurs when receiving data fails
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    logger.info("Handling incoming data.");

    User user = userManager.getUser(ctx.pipeline().channel());
    if (user == null) {
        System.out.println(msg.getClass());
        if (msg instanceof PacketHandshake) {
            PacketHandshake packetHandshake = (PacketHandshake) msg;

            logger.info("Authenticating: " + packetHandshake.getUsername() + " with password "
                    + packetHandshake.getPassword());

            boolean success = userManager.authUser(packetHandshake.getUsername(),
                    packetHandshake.getPassword());

            PacketHandshakeResponse response = new PacketHandshakeResponse();
            response.setResult(success ? HandshakeResult.SUCCESS : HandshakeResult.FAILURE);
            if (success) {
                userManager.createUser(packetHandshake.getUsername(), ctx.channel());
            }
            ChannelFuture future = ctx.channel().writeAndFlush(response);
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if (!future.isSuccess()) {
                        future.cause().printStackTrace();
                    }
                }
            });
            return;
        }
        ctx.pipeline().channel().close();
        return;
    }

    if (msg instanceof Packet) {
        handlePacket(ctx.pipeline().channel(), (Packet) msg);
    }
}

From source file:de.jackwhite20.apex.tcp.pipeline.handler.SocketUpstreamHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap().group(inboundChannel.eventLoop()).channel(PipelineUtils.getChannel())
            .handler(new SocketDownstreamHandler(inboundChannel)).option(ChannelOption.TCP_NODELAY, true)
            // No initial connection should take longer than 4 seconds
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, BackendInfo.DEFAULT_TCP_TIMEOUT)
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(backendInfo.getHost(), backendInfo.getPort());
    downstreamChannel = f.channel();/* w  w  w  .  j  a  v  a  2 s .com*/
    f.addListener((ChannelFutureListener) future -> {

        if (future.isSuccess()) {
            inboundChannel.read();
        } else {
            inboundChannel.close();
        }
    });

    // Add the channel to the channel group
    Apex.getChannelGroup().add(inboundChannel);
}

From source file:de.jackwhite20.apex.udp.pipeline.DatagramUpstreamHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {

    BackendInfo backendInfo = ApexDatagram.getBalancingStrategy().selectBackend("", 0);

    if (backendInfo == null) {
        logger.error("Unable to select a backend server. All down?");
        return;//w ww  . j av a  2 s .  c om
    }

    // Only copy if there is at least one backend server
    ByteBuf copy = datagramPacket.content().copy().retain();

    Bootstrap bootstrap = new Bootstrap().channel(PipelineUtils.getDatagramChannel())
            .handler(new DatagramDownstreamHandler(ctx.channel(), datagramPacket.sender()))
            .group(ctx.channel().eventLoop());

    ChannelFuture channelFuture = bootstrap.bind(0);

    // Add the traffic shaping handler to the channel pipeline
    GlobalTrafficShapingHandler trafficShapingHandler = Apex.getInstance().getTrafficShapingHandler();
    if (trafficShapingHandler != null) {
        // The handler needs to be the first handler in the pipeline
        channelFuture.channel().pipeline().addFirst(trafficShapingHandler);
    }

    channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {

        Channel channel = channelFuture1.channel();
        if (channelFuture1.isSuccess()) {
            channel.writeAndFlush(new DatagramPacket(copy,
                    new InetSocketAddress(backendInfo.getHost(), backendInfo.getPort())));
        } else {
            ChannelUtil.close(channel);
        }

        // Release the buffer
        copy.release();
    });

    // Keep track of request per second
    if (connectionsPerSecondTask != null) {
        connectionsPerSecondTask.inc();
    }
}

From source file:de.jackwhite20.comix.handler.UpstreamHandler.java

License:Open Source License

public void connectDownstream(ByteBuf initPacket) {
    InetSocketAddress address = (InetSocketAddress) upstreamChannel.remoteAddress();
    TargetData target = this.strategy.selectTarget(address.getHostName(), address.getPort());

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(upstreamChannel.eventLoop()).channel(upstreamChannel.getClass())
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.AUTO_READ, false)
            .option(ChannelOption.SO_TIMEOUT, 5000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
            .handler(downstreamHandler = new DownstreamHandler(client, upstreamChannel));

    ChannelFuture f = bootstrap.connect(target.getHost(), target.getPort());
    downstreamChannel = f.channel();//  w ww  .ja va2 s.  com

    initialPackets.add(initPacket);

    f.addListener((future) -> {
        if (future.isSuccess()) {
            downstreamConnected = true;

            for (ByteBuf packet : initialPackets) {
                downstreamChannel.writeAndFlush(packet);
            }

            Comix.getLogger().log(Level.INFO, "Proxy",
                    "[" + client.getName() + "] <-> [Comix] <-> [" + target.getName() + "] tunneled");
        } else {
            upstreamChannel.close();
        }
    });
}

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  ww .ja  v  a 2s  . c o 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:deathcap.wsmc.web.HTTPHandler.java

License:Apache License

public void sendHttpResponse(ChannelHandlerContext context, FullHttpRequest request,
        FullHttpResponse response) {/*www  .  j av  a 2 s.  c  o m*/
    if (response.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(response.getStatus().toString(), CharsetUtil.UTF_8);
        response.content().writeBytes(buf);
        buf.release();
    }
    setContentLength(response, response.content().readableBytes());

    ChannelFuture future = context.channel().writeAndFlush(response);
    if (!isKeepAlive(request) || response.getStatus().code() != 200) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

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;// w ww .  j  a va2s. c om
        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.bus.net.ServerHandler.java

License:Open Source License

public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/* www . jav  a2s .c  o m*/
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);

    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200)
        f.addListener(ChannelFutureListener.CLOSE);
}

From source file:divconq.ctp.net.CtpHandler.java

License:Open Source License

@Override
public void send(ByteBuf buf, ChannelFutureListener listener) {
    try {/*w  w w .j a va2  s. c o m*/
        if (this.chan != null) {
            ChannelFuture future = this.chan.writeAndFlush(buf);

            if (listener != null)
                future.addListener(listener);
        }
    } catch (Exception x) {
        Logger.error("Error writing Ctp buffer: " + x);

        this.close();
    }
}

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);//from  w w  w.  j  av a  2s .  c o  m
        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);
        }
    });
}