Example usage for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS

List of usage examples for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS

Introduction

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

Prototype

ChannelOption CONNECT_TIMEOUT_MILLIS

To view the source code for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.

Click Source Link

Usage

From source file:TestTCP.java

License:Open Source License

public static void main(String... args) throws Throwable {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTP test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);/*from ww w . j ava  2 s. c  o  m*/
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final TCPSocket socket = new TCPSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("http://") ? "" : "http://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:TestSSL.java

License:Open Source License

public static void main(String[] args) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTPS test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);/*from w w  w .j a  v a2  s  .  co m*/
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final SSLSocket socket = new SSLSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("https://") ? "" : "https://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:NettyHttpListner.java

License:Apache License

public void start() {

    System.out.println("Starting the server...");
    System.out.println("Starting Inbound Http Listner on Port " + this.port);

    // Configure SSL.
    SslContext sslCtx = null;/*from   w w  w.j a  v  a2s  . co  m*/
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SSLException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize);
    //        bossGroup = new NioEventLoopGroup(bossGroupSize);
    //        workerGroup = new NioEventLoopGroup(workerGroupSize);

    try {
        ServerBootstrap b = new ServerBootstrap();

        //            b.commonEventLoopGroup(bossGroup, workerGroup)
        b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                        new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx))
                .childOption(ChannelOption.AUTO_READ, false);

        b.option(ChannelOption.TCP_NODELAY, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);

        b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_SNDBUF, 1048576);

        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        Channel ch = null;
        try {
            ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("Inbound Listner Started");
        } catch (InterruptedException e) {
            System.out.println("Exception caught");
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx//w w w. j av a2  s. c om
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            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:be.yildizgames.module.network.netty.client.ClientNetty.java

License:MIT License

/**
 * Set the time out, in milliseconds./*  w ww  .  j  av a  2  s.  c  o m*/
 *
 * @param timeout Timeout value.
 */
public void setTimeOut(final int timeout) {
    this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

/**
 * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture.
 * sessionClientToReplica is replaced with the new connection. Removed redundant
 * code./*from  www .j  ava 2 s.  c o  m*/
 */
public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {

    String str = this.clientId + ":" + replicaId;
    PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray());
    SecretKey authKey = fac.generateSecret(spec);

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec);
    b.handler(getChannelInitializer());

    ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId));

    NettyClientServerSession ncss = new NettyClientServerSession(channelFuture.channel(), replicaId);
    sessionClientToReplica.put(replicaId, ncss);

    return channelFuture;
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) {
    try {/*from  w w  w.  j  a va  2  s . co  m*/

        this.controller = controller;
        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        sessionReplicaToClient = new ConcurrentHashMap<>();
        rl = new ReentrantReadWriteLock();

        // Configure the server.

        serverPipelineFactory = new NettyServerPipelineFactory(this, sessionReplicaToClient, controller, rl);

        EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreads);
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, tcpSendBufferSize)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec)
                .option(ChannelOption.SO_BACKLOG, connectionBacklog)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(serverPipelineFactory.getDecoder());
                        ch.pipeline().addLast(serverPipelineFactory.getEncoder());
                        ch.pipeline().addLast(serverPipelineFactory.getHandler());
                    }
                }).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true);
        String myAddress;
        String confAddress = controller.getStaticConf()
                .getRemoteAddress(controller.getStaticConf().getProcessId()).getAddress().getHostAddress();

        if (InetAddress.getLoopbackAddress().getHostAddress().equals(confAddress)) {

            myAddress = InetAddress.getLoopbackAddress().getHostAddress();

        }

        else if (controller.getStaticConf().getBindAddress().equals("")) {

            myAddress = InetAddress.getLocalHost().getHostAddress();

            // If Netty binds to the loopback address, clients will not be able to connect
            // to replicas.
            // To solve that issue, we bind to the address supplied in config/hosts.config
            // instead.
            if (InetAddress.getLoopbackAddress().getHostAddress().equals(myAddress)
                    && !myAddress.equals(confAddress)) {

                myAddress = confAddress;
            }

        } else {

            myAddress = controller.getStaticConf().getBindAddress();
        }

        int myPort = controller.getStaticConf().getPort(controller.getStaticConf().getProcessId());

        ChannelFuture f = b.bind(new InetSocketAddress(myAddress, myPort)).sync();

        logger.info("ID = " + controller.getStaticConf().getProcessId());
        logger.info("N = " + controller.getCurrentViewN());
        logger.info("F = " + controller.getCurrentViewF());
        logger.info("Port (client <-> server) = "
                + controller.getStaticConf().getPort(controller.getStaticConf().getProcessId()));
        logger.info("Port (server <-> server) = "
                + controller.getStaticConf().getServerToServerPort(controller.getStaticConf().getProcessId()));
        logger.info("requestTimeout = " + controller.getStaticConf().getRequestTimeout());
        logger.info("maxBatch = " + controller.getStaticConf().getMaxBatchSize());
        if (controller.getStaticConf().getUseSignatures() == 1)
            logger.info("Using Signatures");
        else if (controller.getStaticConf().getUseSignatures() == 2)
            logger.info("Using benchmark signature verification");
        logger.info("Binded replica to IP address " + myAddress);
        // ******* EDUARDO END **************//

        /* Tulio Ribeiro */
        // SSL/TLS
        logger.info("SSL/TLS enabled, protocol version: {}",
                controller.getStaticConf().getSSLTLSProtocolVersion());

        /* Tulio Ribeiro END */

        mainChannel = f.channel();

    } catch (InterruptedException | UnknownHostException ex) {
        logger.error("Failed to create Netty communication system", ex);
    }
}

From source file:blazingcache.network.netty.NettyConnector.java

License:Apache License

public NettyChannel connect() throws Exception {
    if (ssl) {/*w  w  w  .  j a  va2 s .  co  m*/
        this.sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    }
    group = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    channel = new NettyChannel(host + ":" + port, ch, callbackExecutor, NettyConnector.this);
                    channel.setMessagesReceiver(receiver);
                    if (ssl) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                    }
                    if (socketTimeout > 0) {
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout));
                    }
                    ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                    ch.pipeline().addLast("lengthbaseddecoder",
                            new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    //
                    ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                    ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                    ch.pipeline().addLast(new InboundMessageHandler(channel));
                }
            });

    ChannelFuture f = b.connect(host, port).sync();
    socketchannel = f.channel();
    return channel;

}

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override/*from w  ww . j a  v a 2 s.c o m*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    });

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}

From source file:cc.agentx.server.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {//from ww w  .  jav  a 2s  .  com
        ByteBuf byteBuf = (ByteBuf) msg;
        if (!byteBuf.hasArray()) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, bytes);

            if (!requestParsed) {
                if (!exposedRequest) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes == null) {
                        log.info("\tClient -> Proxy           \tHalf Request");
                        return;
                    }
                }
                XRequest xRequest = requestWrapper.parse(bytes);
                String host = xRequest.getHost();
                int port = xRequest.getPort();
                int dataLength = xRequest.getSubsequentDataLength();
                if (dataLength > 0) {
                    byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length);
                    if (exposedRequest) {
                        tailData = wrapper.unwrap(tailData);
                        if (tailData != null) {
                            tailDataBuffer.write(tailData, 0, tailData.length);
                        }
                    } else {
                        tailDataBuffer.write(tailData, 0, tailData.length);
                    }
                }
                log.info("\tClient -> Proxy           \tTarget {}:{}{}", host, port,
                        DnsCache.isCached(host) ? " [Cached]" : "");
                if (xRequest.getAtyp() == XRequest.Type.DOMAIN) {
                    try {
                        host = DnsCache.get(host);
                        if (host == null) {
                            host = xRequest.getHost();
                        }
                    } catch (UnknownHostException e) {
                        log.warn("\tClient <- Proxy           \tBad DNS! ({})", e.getMessage());
                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        return;
                    }
                }

                Promise<Channel> promise = ctx.executor().newPromise();
                promise.addListener(new FutureListener<Channel>() {
                    @Override
                    public void operationComplete(final Future<Channel> future) throws Exception {
                        final Channel outboundChannel = future.getNow();
                        if (future.isSuccess()) {
                            // handle tail
                            byte[] tailData = tailDataBuffer.toByteArray();
                            tailDataBuffer.close();
                            if (tailData.length > 0) {
                                log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length);
                            }
                            outboundChannel
                                    .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData)
                                            : Unpooled.EMPTY_BUFFER)
                                    .addListener(channelFuture -> {
                                        // task handover
                                        outboundChannel.pipeline()
                                                .addLast(new XRelayHandler(ctx.channel(), wrapper, false));
                                        ctx.pipeline()
                                                .addLast(new XRelayHandler(outboundChannel, wrapper, true));
                                        ctx.pipeline().remove(XConnectHandler.this);
                                    });

                        } else {
                            if (ctx.channel().isActive()) {
                                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

                final String finalHost = host;
                bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    if (ctx.channel().isActive()) {
                                        log.warn("\tClient <- Proxy           \tBad Ping! ({}:{})", finalHost,
                                                port);
                                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                                .addListener(ChannelFutureListener.CLOSE);
                                    }
                                }
                            }
                        });

                requestParsed = true;
            } else {
                bytes = wrapper.unwrap(bytes);
                if (bytes != null)
                    tailDataBuffer.write(bytes, 0, bytes.length);
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}