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:org.ethereum.net.server.PeerServerImpl.java

License:Open Source License

public void start(int port) {
    // TODO review listening use
    listening = true;/*  w w  w. j a  v  a  2 s.c om*/

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, "");

    ethereumListener.trace("Listening on port " + port);

    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());

        b.handler(new LoggingHandler());
        b.childHandler(ethereumChannelInitializer);

        // Start the client.
        logger.info("Listening for incoming connections, port: [{}] ", port);
        logger.info("NodeId: [{}] ", Hex.toHexString(config.nodeId()));

        ChannelFuture f = b.bind(port).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
        logger.debug("Connection is closed");

        // TODO review listening use
        listening = false;
    } catch (Exception e) {
        logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName());
        throw new Error("Server Disconnected");
    } finally {
        workerGroup.shutdownGracefully();

    }
}

From source file:org.glassfish.jersey.netty.connector.NettyConnector.java

License:Open Source License

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {

    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();

    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort()
            : "https".equals(requestUri.getScheme()) ? 443 : 80;

    try {//from  w  w w  . j a  va2  s  .  c o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();

                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true,
                            ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }

                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);

                    final String userName = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_PASSWORD, String.class);

                    p.addLast(new HttpProxyHandler(
                            new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()),
                            userName, password));
                }

                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback,
                        settableFuture));
            }
        });

        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(),
                ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }

        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();

        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                    throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };

        ch.closeFuture().addListener(closeListener);

        HttpRequest nettyRequest;

        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }

        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }

        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());

        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }

        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);

            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });

            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);

                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });

            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);

            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }

    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }

    return settableFuture;
}

From source file:org.graylog2.gelfclient.transport.GelfTcpTransport.java

License:Apache License

@Override
protected void createBootstrap(final EventLoopGroup workerGroup) {
    final Bootstrap bootstrap = new Bootstrap();
    final GelfSenderThread senderThread = new GelfSenderThread(queue);

    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
            .option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay())
            .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
            .remoteAddress(config.getRemoteAddress()).handler(new ChannelInitializer<SocketChannel>() {
                @Override//  w  w w .ja v a  2  s .  c o  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (config.isTlsEnabled()) {
                        LOG.debug("TLS enabled.");
                        final SslContext sslContext;

                        if (!config.isTlsCertVerificationEnabled()) {
                            // If the cert should not be verified just use an insecure trust manager.
                            LOG.debug("TLS certificate verification disabled!");
                            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
                        } else if (config.getTlsTrustCertChainFile() != null) {
                            // If a cert chain file is set, use it.
                            LOG.debug("TLS certificate chain file: {}", config.getTlsTrustCertChainFile());
                            sslContext = SslContext.newClientContext(config.getTlsTrustCertChainFile());
                        } else {
                            // Otherwise use the JVM default cert chain.
                            sslContext = SslContext.newClientContext();
                        }

                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    }

                    // We cannot use GZIP encoding for TCP because the headers contain '\0'-bytes then.
                    // The graylog2-server uses '\0'-bytes as delimiter for TCP frames.
                    ch.pipeline().addLast(new GelfMessageJsonEncoder());
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                            // We do not receive data.
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            senderThread.start(ctx.channel());
                        }

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            LOG.info("Channel disconnected!");
                            senderThread.stop();
                            scheduleReconnect(ctx.channel().eventLoop());
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            LOG.error("Exception caught", cause);
                        }
                    });
                }
            });

    if (config.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, config.getSendBufferSize());
    }

    bootstrap.connect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                LOG.debug("Connected!");
            } else {
                LOG.error("Connection failed: {}", future.cause().getMessage());
                scheduleReconnect(future.channel().eventLoop());
            }
        }
    });
}

From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingClient.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyClientConfig.getClientWorkerThreads(),
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//from   ww  w. ja  v  a  2  s .  com
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (nettyClientConfig.isUseTLS()) {
                        if (null != sslContext) {
                            pipeline.addFirst(defaultEventExecutorGroup, "sslHandler",
                                    sslContext.newHandler(ch.alloc()));
                            log.info("Prepend SSL handler");
                        } else {
                            log.warn("Connections are insecure as SSLContext is null!");
                        }
                    }
                    pipeline.addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(),
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),
                            new NettyConnectManageHandler(), new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                NettyRemotingClient.this.scanResponseTable();
            } catch (Throwable e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);

    if (this.channelEventListener != null) {
        this.nettyEventExecutor.start();
    }
}

From source file:org.hornetq.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public synchronized void start() {
    if (channelClazz != null) {
        return;/*from ww  w .j  a va2 s . com*/
    }

    int threadsToUse;

    if (nioRemotingThreads == -1) {
        // Default to number of cores * 3

        threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    } else {
        threadsToUse = this.nioRemotingThreads;
    }

    if (useNioGlobalWorkerPool) {
        channelClazz = NioSocketChannel.class;
        group = SharedNioEventLoopGroup.getInstance(threadsToUse);
    } else {
        channelClazz = NioSocketChannel.class;
        group = new NioEventLoopGroup(threadsToUse);
    }
    // if we are a servlet wrap the socketChannelFactory
    if (useServlet) {
        // TODO: This will be replaced by allow upgrade HTTP connection from Undertow.;
    }
    bootstrap = new Bootstrap();
    bootstrap.channel(channelClazz);
    bootstrap.group(group);

    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);

    if (connectTimeoutMillis != -1) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false));
    channelGroup = new DefaultChannelGroup("hornetq-connector", GlobalEventExecutor.INSTANCE);

    final SSLContext context;
    if (sslEnabled) {
        try {
            // HORNETQ-680 - override the server-side config if client-side system properties are set
            String realKeyStorePath = keyStorePath;
            String realKeyStoreProvider = keyStoreProvider;
            String realKeyStorePassword = keyStorePassword;
            if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(HORNETQ_KEYSTORE_PROVIDER_PROP_NAME) != null) {
                realKeyStoreProvider = System.getProperty(HORNETQ_KEYSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(HORNETQ_KEYSTORE_PATH_PROP_NAME) != null) {
                realKeyStorePath = System.getProperty(HORNETQ_KEYSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(HORNETQ_KEYSTORE_PASSWORD_PROP_NAME) != null) {
                realKeyStorePassword = System.getProperty(HORNETQ_KEYSTORE_PASSWORD_PROP_NAME);
            }

            String realTrustStorePath = trustStorePath;
            String realTrustStoreProvider = trustStoreProvider;
            String realTrustStorePassword = trustStorePassword;
            if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME);
            }

            if (System.getProperty(HORNETQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) {
                realTrustStoreProvider = System.getProperty(HORNETQ_TRUSTSTORE_PROVIDER_PROP_NAME);
            }
            if (System.getProperty(HORNETQ_TRUSTSTORE_PATH_PROP_NAME) != null) {
                realTrustStorePath = System.getProperty(HORNETQ_TRUSTSTORE_PATH_PROP_NAME);
            }
            if (System.getProperty(HORNETQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) {
                realTrustStorePassword = System.getProperty(HORNETQ_TRUSTSTORE_PASSWORD_PROP_NAME);
            }
            context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword,
                    realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
        } catch (Exception e) {
            close();
            IllegalStateException ise = new IllegalStateException(
                    "Unable to create NettyConnector for " + host + ":" + port);
            ise.initCause(e);
            throw ise;
        }
    } else {
        context = null; // Unused
    }

    if (context != null && useServlet) {
        // TODO: Fix me
        //bootstrap.setOption("sslContext", context);
    }

    bootstrap.handler(new ChannelInitializer<Channel>() {
        public void initChannel(Channel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled && !useServlet) {
                SSLEngine engine = context.createSSLEngine();

                engine.setUseClientMode(true);

                engine.setWantClientAuth(true);

                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();

                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        HornetQClientLogger.LOGGER.invalidCipherSuite(SSLSupport
                                .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }

                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(
                                SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        HornetQClientLogger.LOGGER.invalidProtocol(
                                SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }

                SslHandler handler = new SslHandler(engine);

                pipeline.addLast(handler);
            }

            if (httpEnabled) {
                pipeline.addLast(new HttpRequestEncoder());

                pipeline.addLast(new HttpResponseDecoder());

                pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                pipeline.addLast(new HttpHandler());
            }

            if (httpUpgradeEnabled) {
                // prepare to handle a HTTP 101 response to upgrade the protocol.
                final HttpClientCodec httpClientCodec = new HttpClientCodec();
                pipeline.addLast(httpClientCodec);
                pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec));
            }
            pipeline.addLast(new HornetQFrameDecoder2());

            pipeline.addLast(new HornetQClientChannelHandler(channelGroup, handler, new Listener()));
        }
    });

    if (batchDelay > 0) {
        flusher = new BatchFlusher();

        batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay,
                TimeUnit.MILLISECONDS);
    }

    HornetQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION);
}

From source file:org.jdiameter.client.impl.transport.tcp.netty.TCPTransportClient.java

License:Open Source License

public void start() throws InterruptedException {
    logger.debug("Starting TCP Transport on [{}]", socketDescription);
    if (isConnected()) {
        logger.debug("TCP Transport already started, [{}]", socketDescription);
        return;/*from   w  w w  .j  ava 2s .c  o  m*/
    }

    this.workerGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", new DiameterMessageDecoder(parentConnection, parser));
                    pipeline.addLast("encoder", new DiameterMessageEncoder(parser));
                    pipeline.addLast(eventExecutorGroup, "msgHandler",
                            new DiameterMessageHandler(parentConnection));
                }
            });

    this.channel = bootstrap.remoteAddress(destAddress).connect().sync().channel();
    logger.debug("TCP Transport connected successfully, [{}]", socketDescription);

    parentConnection.onConnected();
}

From source file:org.jfxvnc.ui.service.VncRenderService.java

License:Apache License

private boolean connect() throws Exception {
    connectProperty.set(true);/*from w w  w. j ava2 s. c  o  m*/
    shutdown();
    workerGroup = new NioEventLoopGroup();

    String host = config.hostProperty().get();
    int port = config.portProperty().get() > 0 ? config.portProperty().get() : CONNECT_PORT;

    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.CONNECT_TIMEOUT_MILLIS, 5000);

    b.handler(new ProtocolInitializer(VncRenderService.this, config));

    logger.info("try to connect to {}:{}", host, port);
    ChannelFuture f = b.connect(host, port);
    f.await(5000);

    connectProperty.set(f.isSuccess());
    logger.info("connection {}", connectProperty.get() ? "established" : "failed");
    if (f.isCancelled()) {
        logger.warn("connection aborted");
    } else if (!f.isSuccess()) {
        logger.error("connection failed", f.cause());
        exceptionCaughtProperty.set(f.cause() != null ? f.cause()
                : new Exception("connection failed to host: " + host + ":" + port));
    }
    return connectProperty.get();
}

From source file:org.jupiter.transport.netty.NettyTcpConnector.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    Bootstrap boot = bootstrap();// w  w w  .  j  a va  2  s.c  o m

    NettyConfig.NettyTcpConfigGroup.ChildConfig child = childConfig;

    // child options
    boot.option(ChannelOption.SO_REUSEADDR, child.isReuseAddress())
            .option(ChannelOption.SO_KEEPALIVE, child.isKeepAlive())
            .option(ChannelOption.TCP_NODELAY, child.isTcpNoDelay())
            .option(ChannelOption.ALLOW_HALF_CLOSURE, child.isAllowHalfClosure());
    if (child.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.option(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.option(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getIpTos() > 0) {
        boot.option(ChannelOption.IP_TOS, child.getIpTos());
    }
    if (child.getConnectTimeoutMillis() > 0) {
        boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, child.getConnectTimeoutMillis());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.option(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.jupiter.transport.netty.NettyUdtConnector.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    Bootstrap boot = bootstrap();//w ww.j a  v a2  s  .com

    NettyUdtConfigGroup.ChildConfig child = childConfig;

    // child options
    boot.option(ChannelOption.SO_REUSEADDR, child.isReuseAddress());
    if (child.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.option(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.option(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getConnectTimeoutMillis() > 0) {
        boot.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, child.getConnectTimeoutMillis());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.option(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.kobeyoung81.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//w ww . j a  v  a 2s.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(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
                //System.out.println(request.toString());
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientHandler(promise));
    //System.out.println(request.host() +":"+ request.port());
    //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080);
    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}