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:madtest.common.netty.study.chapter11.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // //from   w  ww  .  jav  a2  s  .  c o m
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaderUtil.setContentLength(res, res.content().readableBytes());
    }

    // ?Keep-Alive
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:md.mgmt.facade.IndexServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    logger.info(String.valueOf(msg));
    long start = System.currentTimeMillis();
    String respStr = commandMapper.selectService((String) msg);
    long end = System.currentTimeMillis();
    logger.info("resp:" + respStr);
    logger.info("time spend: " + (end - start));
    ChannelFuture f = ctx.writeAndFlush(respStr);
    f.addListener(ChannelFutureListener.CLOSE);
}

From source file:me.bigteddy98.mcproxy.protocol.handlers.ClientSideHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    incomingChannel = ctx.channel();//from   ww  w  .  ja  v  a2s  .co  m
    networkManager.clientsidePipeline = ctx.pipeline();

    Bootstrap bootstrab = new Bootstrap();
    bootstrab.group(incomingChannel.eventLoop());
    bootstrab.channel(ctx.channel().getClass());
    bootstrab.handler(serverboundConnectionInitializer = new ServerboundConnectionInitializer(networkManager,
            incomingChannel));
    bootstrab.option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = bootstrab.connect(hostname, port);

    outgoingChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                incomingChannel.read();
            } else {
                incomingChannel.close();
            }
        }
    });
}

From source file:me.bigteddy98.movingmotd.ClientSideConnection.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    this.networkManager.incomingChannel = ctx.channel();
    this.networkManager.clientsidePipeline = ctx.pipeline();

    Bootstrap bootstrab = new Bootstrap();
    bootstrab.group(networkManager.incomingChannel.eventLoop());
    bootstrab.channel(ctx.channel().getClass());
    bootstrab.handler(new ServerSideConnectionInitialization(networkManager));
    bootstrab.option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = bootstrab.connect(this.toHostname, this.toPort);
    f.addListener(new ChannelFutureListener() {
        @Override//from  w  w w  .j  a  va2 s . c o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                networkManager.incomingChannel.read();
            } else {
                networkManager.incomingChannel.close();
            }
        }
    });
    this.outgoingChannel = f.channel();
}

From source file:me.binf.socks5.client.proxy.HexDumpProxyFrontendHandler.java

License:Apache License

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

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);

    outboundChannel = f.channel();//w  ww .  j  a  va2s  .  co m
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                proxyService.noticeView("?" + remoteHost + ":" + remotePort + "?!");
                inboundChannel.read();
            } else {
                proxyService.noticeView("?" + remoteHost + ":" + remotePort + "!");
                inboundChannel.close();
            }
        }
    });
}

From source file:me.ferrybig.javacoding.teamspeakconnector.internal.TeamspeakIO.java

License:Open Source License

public Future<ComplexResponse> sendPacket(ComplexRequest req, SendBehaviour sendBehaviour) {
    if (closed) {
        if (sendBehaviour != SendBehaviour.NORMAL) {
            return this.closeFuture;
        }/*from w ww.j  a  v  a2s .  c o m*/
        return channel.eventLoop().newFailedFuture(new TeamspeakException("Channel closed"));
    }
    Promise<ComplexResponse> prom = channel.eventLoop().newPromise();
    ChannelFuture future;
    synchronized (incomingQueue) {
        if (closed) {
            if (sendBehaviour != SendBehaviour.NORMAL) {
                return this.closeFuture;
            }
            return prom.setFailure(new TeamspeakException("Channel closed"));
        }
        incomingQueue.offer(new PendingPacket(prom, req, sendBehaviour));
        future = channel.writeAndFlush(req);
    }
    future.addListener(upstream -> {
        assert upstream == future;
        if (sendBehaviour == SendBehaviour.FORCE_CLOSE_CONNECTION) {
            channel.eventLoop().schedule(() -> {
                if (channel.isActive()) {
                    LOG.fine("Closing channel by timeout");
                    channel.close();
                }
            }, 10, TimeUnit.SECONDS);
        }
        if (!upstream.isSuccess()) {
            synchronized (incomingQueue) {
                if (incomingQueue.removeIf(prom::equals)) {
                    prom.setFailure(new TeamspeakException("Exception during sending", upstream.cause()));
                }
            }
        }
    });
    if (sendBehaviour == SendBehaviour.CLOSE_CONNECTION
            || sendBehaviour == SendBehaviour.FORCE_CLOSE_CONNECTION) {
        prom.addListener(upstream -> {
            assert upstream == prom;
            if (prom.isSuccess()) {
                synchronized (incomingQueue) {
                    this.closed = true;
                }
                channel.close();
                LOG.fine("Closing channel because sendmessage asked it");
            }
        });
    }

    return prom;
}

From source file:me.ferrybig.javacoding.teamspeakconnector.TeamspeakApi.java

License:Open Source License

public Future<TeamspeakConnection> connect(SocketAddress addr) {
    Promise<TeamspeakConnection> prom = this.group.next().newPromise();
    ChannelFuture channel = openChannel(addr, new TeamspeakConnectionInitizer(prom, 20000), 20000);
    channel.addListener(future -> {
        if (!channel.isSuccess()) {
            prom.setFailure(new TeamspeakException("Connection failed", channel.cause()));
        }//from   w  w w  .  j a va2s  .com
    });
    return prom;
}

From source file:me.ferrybig.javacoding.webmapper.netty.WebServerHandler.java

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }/*from   w w  w  .  ja  v a2  s.  co m*/
}

From source file:me.ferrybig.p2pnetwork.LocalConnection.java

public void close(CloseReason reason, boolean prepare) {
    ChannelFuture f = this.channel.write(new ExitPacket(reason, prepare));
    if (!prepare)
        f.addListener(ChannelFutureListener.CLOSE);
}

From source file:me.ferrybig.p2pnetwork.Main.java

private void startIncomingConnectionThread(int port) {
    ServerBootstrap server = new ServerBootstrap();
    server.group(group);//from  w  w w . j a va  2  s.c o m
    server.channel(NioServerSocketChannel.class);
    server.option(ChannelOption.SO_BACKLOG, 128);
    server.childOption(ChannelOption.SO_KEEPALIVE, true);
    server.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            if (blocked.containsKey(((InetSocketAddress) ch.remoteAddress()).getAddress())) {
                LOG.info(ch + "Rejected at socket level");
                ch.close();
                return;
            }
            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new PacketEncoder());
            ch.pipeline().addLast(new PacketDecoder());
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new ServerBootstrapConnector(addr, incomingListener));
            clientsIn.add(ch);
            ch.closeFuture().addListener(e1 -> {
                clientsIn.remove(ch);
            });
        }
    });
    ChannelFuture f = server.bind(port);
    f.addListener(e -> {
        this.servers.add((ServerChannel) f.channel());
        f.channel().closeFuture().addListener(e1 -> {
            this.servers.remove((ServerChannel) f.channel());
        });
    });
}