Search in sources :

Example 86 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project jgnash by ccavanaugh.

the class AttachmentTransferClient method connectToServer.

/**
     * Starts the connection with the lock server.
     *
     * @param host remote host
     * @param port connection port
     * @param password connection password
     * @return {@code true} if successful
     */
boolean connectToServer(final String host, final int port, final char[] password) {
    boolean result = false;
    // If a password has been specified, create an EncryptionManager
    if (password != null && password.length > 0) {
        encryptionManager = new EncryptionManager(password);
    }
    final Bootstrap bootstrap = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    transferHandler = new NettyTransferHandler(tempDirectory, encryptionManager);
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new Initializer()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConnectionFactory.getConnectionTimeout() * 1000).option(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Start the connection attempt.
        channel = bootstrap.connect(host, port).sync().channel();
        result = true;
        logger.info("Connection made with File Transfer Server");
    } catch (final InterruptedException e) {
        logger.log(Level.SEVERE, "Failed to connect to the File Transfer Server", e);
        disconnectFromServer();
    }
    return result;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EncryptionManager(jgnash.util.EncryptionManager) ChannelInitializer(io.netty.channel.ChannelInitializer) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NettyTransferHandler(jgnash.engine.attachment.NettyTransferHandler)

Example 87 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project jgnash by ccavanaugh.

the class DistributedLockManager method connectToServer.

/**
     * Starts the connection with the lock server.
     *
     * @param password connection password
     * @return {@code true} if successful
     */
public boolean connectToServer(final char[] password) {
    boolean result = false;
    // If a password has been specified, create an EncryptionManager
    if (password != null && password.length > 0) {
        encryptionManager = new EncryptionManager(password);
    }
    final Bootstrap bootstrap = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new Initializer()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConnectionFactory.getConnectionTimeout() * 1000).option(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Start the connection attempt.
        channel = bootstrap.connect(host, port).sync().channel();
        // send this channels uuid
        channel.writeAndFlush(encrypt(UUID_PREFIX + uuid) + EOL_DELIMITER).sync();
        result = true;
        logger.info("Connection made with Distributed Lock Server");
    } catch (final InterruptedException e) {
        logger.log(Level.SEVERE, "Failed to connect to Distributed Lock Server", e);
        disconnectFromServer();
    }
    return result;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EncryptionManager(jgnash.util.EncryptionManager) ChannelInitializer(io.netty.channel.ChannelInitializer) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 88 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project flink by apache.

the class NettyClient method init.

void init(final NettyProtocol protocol, NettyBufferPool nettyBufferPool) throws IOException {
    checkState(bootstrap == null, "Netty client has already been initialized.");
    this.protocol = protocol;
    long start = System.currentTimeMillis();
    bootstrap = new Bootstrap();
    switch(config.getTransportType()) {
        case NIO:
            initNioBootstrap();
            break;
        case EPOLL:
            initEpollBootstrap();
            break;
        case AUTO:
            if (Epoll.isAvailable()) {
                initEpollBootstrap();
                LOG.info("Transport type 'auto': using EPOLL.");
            } else {
                initNioBootstrap();
                LOG.info("Transport type 'auto': using NIO.");
            }
    }
    // --------------------------------------------------------------------
    // Configuration
    // --------------------------------------------------------------------
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    // Timeout for new connections
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getClientConnectTimeoutSeconds() * 1000);
    // Pooled allocator for Netty's ByteBuf instances
    bootstrap.option(ChannelOption.ALLOCATOR, nettyBufferPool);
    // Receive and send buffer size
    int receiveAndSendBufferSize = config.getSendAndReceiveBufferSize();
    if (receiveAndSendBufferSize > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, receiveAndSendBufferSize);
        bootstrap.option(ChannelOption.SO_RCVBUF, receiveAndSendBufferSize);
    }
    try {
        clientSSLContext = config.createClientSSLContext();
    } catch (Exception e) {
        throw new IOException("Failed to initialize SSL Context for the Netty client", e);
    }
    long end = System.currentTimeMillis();
    LOG.info("Successful initialization (took {} ms).", (end - start));
}
Also used : Bootstrap(io.netty.bootstrap.Bootstrap) IOException(java.io.IOException) IOException(java.io.IOException)

Example 89 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project apn-proxy by apn-proxy.

the class ApnProxyUserAgentTunnelHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        final HttpRequest httpRequest = (HttpRequest) msg;
        //Channel uaChannel = uaChannelCtx.channel();
        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).option(ChannelOption.AUTO_READ, false).handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel()));
        final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel().attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();
        // set local address
        if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
            bootstrap.localAddress(new InetSocketAddress((ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
        }
        bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(final ChannelFuture future1) throws Exception {
                if (future1.isSuccess()) {
                    if (apnProxyRemote.isAppleyRemoteRule()) {
                        uaChannelCtx.pipeline().remove("codec");
                        uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                        uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);
                        // add relay handler
                        uaChannelCtx.pipeline().addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel()));
                        future1.channel().writeAndFlush(Unpooled.copiedBuffer(constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future2) throws Exception {
                                if (!future2.channel().config().getOption(ChannelOption.AUTO_READ)) {
                                    future2.channel().read();
                                }
                            }
                        });
                    } else {
                        HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established"));
                        uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future2) throws Exception {
                                // remove handlers
                                uaChannelCtx.pipeline().remove("codec");
                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);
                                // add relay handler
                                uaChannelCtx.pipeline().addLast(new ApnProxyRelayHandler("UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel()));
                            }
                        });
                    }
                } else {
                    if (uaChannelCtx.channel().isActive()) {
                        uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                    }
                }
            }
        });
    }
    ReferenceCountUtil.release(msg);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ApnProxyRemote(com.xx_dev.apn.proxy.remotechooser.ApnProxyRemote) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 90 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project apn-proxy by apn-proxy.

the class TestProxyWithNetty method test.

public void test(String host, String path) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new TestHttpClientChannelInitializer());
        // Make the connection attempt.
        Channel ch = b.connect("127.0.0.1", ApnProxyConfig.getConfig().getPort()).sync().channel();
        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://" + host + path);
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        //request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
        // Send the HTTP request.
        ch.writeAndFlush(request);
        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Channel(io.netty.channel.Channel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)163 Channel (io.netty.channel.Channel)81 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)73 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)68 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelFuture (io.netty.channel.ChannelFuture)62 EventLoopGroup (io.netty.channel.EventLoopGroup)61 Test (org.junit.Test)61 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)49 InetSocketAddress (java.net.InetSocketAddress)49 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)37 SocketChannel (io.netty.channel.socket.SocketChannel)33 ChannelPipeline (io.netty.channel.ChannelPipeline)31 LocalAddress (io.netty.channel.local.LocalAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 LocalChannel (io.netty.channel.local.LocalChannel)22 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)20 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18