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:me.bigteddy98.slimeportal.protocol.handlers.ClientSideHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    if (outgoingChannel.isActive()) {
        ByteBuf bufferClone = Unpooled.copiedBuffer((ByteBuf) msg);
        final List<Packet> packets = this.networkManager.handleServerBoundPackets(bufferClone);
        bufferClone.release();//from w  w w.ja  v a2  s  .c om
        if (!packets.isEmpty()) {
            for (final Packet packet : packets) {
                PacketReceiveEvent event = new PacketReceiveEvent();
                packet.onReceive(this.networkManager, event);
                if (event.isCancelled()) {
                    ctx.channel().read();
                    continue;
                }

                PacketDataWrapper excludingSize = new PacketDataWrapper(Unpooled.buffer());
                excludingSize.writeVarInt(packet.getId());
                packet.write(excludingSize);

                final PacketDataWrapper includingSize = new PacketDataWrapper(Unpooled.buffer());
                includingSize.writeVarInt(excludingSize.readableBytes());
                includingSize.writeBytes(excludingSize.getBuffer());
                excludingSize.getBuffer().release();

                outgoingChannel.writeAndFlush(includingSize.getBuffer())
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                packet.onSend(networkManager);
                                if (future.isSuccess()) {
                                    ctx.channel().read();
                                } else {
                                    future.channel().close();
                                }
                            }
                        });
            }
            ((ByteBuf) msg).release();
        } else {
            outgoingChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        ctx.channel().read();
                    } else {
                        future.channel().close();
                    }
                }
            });
        }
    }
}

From source file:me.bigteddy98.slimeportal.protocol.handlers.ServerSideHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf bufferClone = Unpooled.copiedBuffer((ByteBuf) msg);
    final List<Packet> packets = this.networkManager.handleClientBoundPackets(bufferClone);
    bufferClone.release();//from  w ww  . j  a  v a 2  s.  c o  m

    if (!packets.isEmpty()) {
        for (final Packet packet : packets) {
            PacketReceiveEvent event = new PacketReceiveEvent();
            packet.onReceive(this.networkManager, event);
            if (event.isCancelled()) {
                ctx.channel().read();
                continue;
            }

            PacketDataWrapper excludingSize = new PacketDataWrapper(Unpooled.buffer());
            excludingSize.writeVarInt(packet.getId());
            packet.write(excludingSize);

            final PacketDataWrapper includingSize = new PacketDataWrapper(Unpooled.buffer());
            includingSize.writeVarInt(excludingSize.readableBytes());
            includingSize.writeBytes(excludingSize.getBuffer());

            excludingSize.getBuffer().release();
            inboundChannel.writeAndFlush(includingSize.getBuffer()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    packet.onSend(networkManager);
                    if (future.isSuccess()) {
                        ctx.channel().read();
                    } else {
                        future.channel().close();
                    }
                }
            });
        }
        ((ByteBuf) msg).release();
    } else {
        inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    }
}

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();//from   w  w w .jav  a2  s  . c  o 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.melchor9000.net.Socket.java

License:Open Source License

/**
 * Binds the socket to a random port and connects to the remote endpoint
 * asynchronously. Returns a {@link Future} where the task can be managed.
 * @param endpoint remote endpoint to connect
 * @return {@link Future} of the task/*from   w w w  .j av a 2 s .  c  om*/
 */
public @NotNull Future<Void> connectAsync(@NotNull SocketAddress endpoint) {
    return createFuture(bootstrap.connect(endpoint).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            channel = future.channel();
            if (future.isSuccess()) {
                bootstrap = null;
            }
        }
    }));
}

From source file:me.melchor9000.net.Socket.java

License:Open Source License

/**
 * Sends some data stored in the {@link ByteBuf} {@code data}, starting from its
 * current position with a size of {@code bytes}. Depending on the implementation
 * and its options, is possible that the data could not be sent in the moment, or
 * only a portion of it is sent. This is an asynchronous operation, so returns a
 * {@link Future} representing the task.
 * @param data buffer with the data to be sent
 * @param bytes number of bytes to send//from   w ww  .  j ava 2s  .  co m
 * @return a {@link Future} representing this task
 */
public @NotNull Future<Void> sendAsync(ByteBuf data, final int bytes) {
    checkSocketCreated("sendAsync");
    final ByteBuf buff = ByteBufAllocator.DEFAULT.directBuffer(bytes).retain();
    buff.writeBytes(data, 0, bytes);
    return createFuture(channel.writeAndFlush(buff).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            bytesWrote += bytes;
            buff.release();
        }
    }));
}

From source file:me.melchor9000.net.UDPSocket.java

License:Open Source License

public Future<Void> sendAsyncTo(ByteBuf data, final int bytes, InetSocketAddress endpoint) {
    checkSocketCreated("sendAsyncTo");
    final ByteBuf buff = channel.alloc().directBuffer(bytes).retain();
    buff.writeBytes(data, bytes);/*w w w.ja va2s  .co  m*/
    return createFuture(
            channel.writeAndFlush(new DatagramPacket(buff, endpoint)).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    buff.release();
                }
            }));
}

From source file:mmo.server.Server.java

License:Open Source License

public void run(String host, int port) {
    parentGroup = new NioEventLoopGroup();
    childGroup = new NioEventLoopGroup();

    new ServerBootstrap().group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HttpServerCodec(), //
                            new HttpObjectAggregator(65536), //
                            routeHandlerProvider.get());

                }/* w w  w  .j  a  v  a  2 s  .  co m*/
            }).option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(16384)).bind(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        L.error("Error setting up server channel: {}", future.cause(), null);
                        new Thread(() -> { // TODO shutdown program
                            // gracefuller
                            try {
                                shutdown();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } finally {
                                System.exit(1);
                            }
                        }).start();
                    }
                }
            });
}

From source file:nats.client.NatsImpl.java

License:Open Source License

private void connect() {
    synchronized (lock) {
        if (closed) {
            return;
        }// w w  w  . j a v a2s . co  m
    }
    final ServerList.Server server = serverList.nextServer();
    LOGGER.debug("Attempting to connect to {} with user {}", server.getAddress(), server.getUser());
    new Bootstrap().group(eventLoopGroup).remoteAddress(server.getAddress()).channel(NioSocketChannel.class)
            .handler(new NatsChannelInitializer()).connect().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        LOGGER.info("Connection to {} successful", server.getAddress());
                        server.connectionSuccess();
                        synchronized (lock) {
                            channel = future.channel();
                            if (closed) {
                                channel.close();
                            }
                        }
                    } else {
                        LOGGER.warn("Connection to {} failed", server.getAddress());
                        server.connectionFailure();
                        scheduleReconnect();
                    }
                }
            });
}

From source file:nenea.client.operation.UptimeClient.java

License:Apache License

static void connect(Bootstrap b) {
    b.connect().addListener(new ChannelFutureListener() {
        @Override/*from  w w w.  j  a va2 s .  co  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() != null) {
                uptimeHandler.startTime = -1;
                uptimeHandler.println("Failed to connect: " + future.cause());
            }
        }
    });
}

From source file:net.anyflow.menton.http.HttpClient.java

License:Apache License

/**
 * request./* w  w  w.j  a va 2  s.c om*/
 * 
 * @param receiver
 * @return if receiver is not null the request processed successfully,
 *         returns HttpResponse instance, otherwise null.
 */
private HttpResponse request(final MessageReceiver receiver) {
    httpRequest().normalize();
    setDefaultHeaders(httpRequest());

    if (logger.isDebugEnabled()) {
        logger.debug(httpRequest().toString());
    }

    final HttpClientHandler clientHandler = new HttpClientHandler(receiver, httpRequest);

    final EventLoopGroup group = new NioEventLoopGroup(1, new DefaultThreadFactory("client"));
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {

            if ("true".equalsIgnoreCase(Settings.SELF.getProperty("menton.logging.writelogOfNettyLogger"))) {
                ch.pipeline().addLast("log", new LoggingHandler("menton/server", LogLevel.DEBUG));
            }

            if ("https".equalsIgnoreCase(httpRequest().uriObject().getScheme())) {
                SslContext sslCtx = SslContextBuilder.forClient().trustManager(trustManagerFactory).build();

                ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), httpRequest().uriObject().getHost(),
                        httpRequest().uriObject().getPort()));
            }

            ch.pipeline().addLast("codec", new HttpClientCodec());
            ch.pipeline().addLast("inflater", new HttpContentDecompressor());
            ch.pipeline().addLast("chunkAggregator", new HttpObjectAggregator(1048576));
            ch.pipeline().addLast("handler", clientHandler);
        }
    });

    try {
        Channel channel = bootstrap
                .connect(httpRequest().uriObject().getHost(), httpRequest().uriObject().getPort()).sync()
                .channel();
        channel.writeAndFlush(httpRequest);

        if (receiver == null) {
            channel.closeFuture().sync();
            group.shutdownGracefully();

            return clientHandler.httpResponse();
        } else {
            channel.closeFuture().addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    group.shutdownGracefully();
                }
            });

            return null;
        }
    } catch (Exception e) {
        group.shutdownGracefully();
        logger.error(e.getMessage(), e);

        return null;
    }

}