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.wso2.carbon.transport.http.netty.util.server.HttpServer.java

License:Open Source License

/**
 * Start the HttpServer// w  w w  .  ja  v  a 2 s . c om
 */
public void start() {
    bossGroup = new NioEventLoopGroup(this.bossGroupSize);
    workerGroup = new NioEventLoopGroup(this.workerGroupSize);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childOption(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer);
        ChannelFuture ch = b.bind(new InetSocketAddress(TestUtil.TEST_HOST, port));
        ch.sync();
        logger.info("HttpServer started on port " + port);
    } catch (InterruptedException e) {
        logger.error("HTTP Server cannot start on port " + port);
    }
}

From source file:org.wso2.carbon.transport.http.netty.util.server.HttpsServer.java

License:Open Source License

/**
 * Start the HttpsServer/*from  ww w .j a  v a 2  s . c  o m*/
 */
public void start() {
    bossGroup = new NioEventLoopGroup(this.bossGroupSize);
    workerGroup = new NioEventLoopGroup(this.workerGroupSize);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childOption(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(ksName), ksPass);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, ctPass);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, null);
        ((HTTPServerInitializer) channelInitializer).setSslContext(sslContext);

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer);
        ChannelFuture ch = b.bind(new InetSocketAddress(TestUtil.TEST_HOST, port));
        ch.sync();
        logger.info("HttpServer started on port " + port);
    } catch (Exception e) {
        logger.error("HTTP Server cannot start on port " + port);
    }
}

From source file:org.wso2.siddhi.extension.input.transport.http.server.HTTPServer.java

License:Open Source License

/**
 * Start the HTTPServer/*  ww w  .j  av a 2s.  c o  m*/
 */
public void start() {
    bossGroup = new NioEventLoopGroup(this.bossGroupSize);
    workerGroup = new NioEventLoopGroup(this.workerGroupSize);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, backLog);
        b.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
        b.option(ChannelOption.SO_KEEPALIVE, isKeepAlive);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeOut);
        httpServerInitializer = new HTTPServerInitializer();
        httpServerInitializer.setSslContext(sslContext);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(httpServerInitializer);
        ChannelFuture ch = b.bind(new InetSocketAddress(ServerUtil.TEST_HOST, port)).sync();
        logger.info("HTTPServer starting on port " + port);
        if (ch.isSuccess()) {
            logger.info("HTTPServer started on port " + port);
        }
    } catch (InterruptedException e) {
        logger.error("HTTP Server cannot start on port " + port);
    }
}

From source file:org.wyb.sows.client.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) {
        System.err.println("Not able to establish bridge. Inform proxy client.");
        ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
        SocksServerUtils.closeOnFlush(ctx.channel());
    }/*from   w ww  .  j a  va  2s  . com*/

    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                if (SocksServer.isDebug) {
                    System.out.println("Bridge is established. Inform proxy client.");
                }
                SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType());
                resp.setProtocolVersion(request.protocolVersion());
                ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) {
                        ChannelPipeline pipeline = ctx.pipeline();
                        pipeline.remove(SocksServerConnectHandler.this);
                        // ctx.pipeline().addLast(new StringByteCodec());
                        pipeline.addLast(new WebSocketRelayHandler(outboundChannel));
                    }
                });
            } else {
                System.err.println("Not able to establish bridge. Inform proxy client.");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    final Channel inboundChannel = ctx.channel();

    // Add authentication headers
    HttpHeaders authHeader = new DefaultHttpHeaders();
    authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName);
    byte[] nonce = SowsAuthHelper.randomBytes(16);
    String seed = SowsAuthHelper.base64(nonce);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed);
    byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII));
    String token = SowsAuthHelper.base64(sha1);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token);

    // initiating websocket client handler
    final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
            .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise,
            request.host(), request.port(), inboundChannel);
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                }
            });
    if (SocksServer.isDebug) {
        System.out.println("Try to connect to bridge service.");
    }
    b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
                if (SocksServer.isDebug) {
                    System.out.printf("Brige service connection is established. host=%s,port=%d \r\n",
                            bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                }
            } else {
                // Close the connection if the connection attempt has
                // failed.
                System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n",
                        bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

}

From source file:org.wyb.sows.server.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure("./config/serverlog.config");
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  ww w  . ja  va 2 s.c  om
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new WebSocketServerInitializer(sslCtx, new SimpleAuthHandler()));

        Channel ch = b.bind(PORT).sync().channel();
        logger.info("WebSocketServer is started.");
        ch.closeFuture().sync();
        logger.info("WebSocketServer is closed.");
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        logger.info("EventLoopGroups are shutdown.");
    }
}

From source file:pers.zlf.sslocal.handler.shadowsocks.ShadowsocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    final Option option = ShadowsocksClient.getShadowsocksOption(ctx.channel());
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*ww w  . j a  v a  2 s  .com*/
        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(ShadowsocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(
                                        new ShadowsocksMessageCodec(CryptoFactory
                                                .createCrypto(option.getMethod(), option.getPassword())),
                                        new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));

                                outboundChannel.writeAndFlush(request);
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                ChannelUtils.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));

    b.connect(option.getRemoteHost(), option.getRemotePort()).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.
                if (logger.isErrorEnabled()) {
                    logger.error("Failed to connect shadowsocks server", future.cause());
                }

                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                ChannelUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:playground.gregor.vis.CASimVisClient.java

License:Open Source License

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("usage: VisClient <server> <port>");
        System.exit(-1);/*  www . j a  v a  2 s .c o m*/
    }
    String serv = args[0];
    int port = Integer.parseInt(args[1]);

    PeerInfo server = new PeerInfo(serv, port);
    DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();

    // in case client acts as server, which is the reason behind a duplex
    // connection indeed.
    RpcServerCallExecutor executor = new ThreadPoolCallExecutor(3, 100);
    clientFactory.setRpcServerCallExecutor(executor);

    clientFactory.setConnectResponseTimeoutMillis(1000);

    // clientFactory.getRpcServiceRegistry().registerService();

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.handler(clientFactory);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);

    RpcClientChannel channel = clientFactory.peerWith(server, bootstrap);

    BlockingInterface visService = ProtoFrame.FrameServerService.newBlockingStub(channel);
    RpcController cntr = channel.newRpcController();
    clientFactory.getRpcServiceRegistry().registerService(
            ProtoFrame.FrameServerService.newReflectiveBlockingService(new BlockingVisServiceImpl(null, null)));

    new CASimVisClient(visService, cntr).run();
    //
    // channel.close();
    // executor.shutdown();
    // System.exit(0);
}

From source file:poke.client.comm.CommConnection.java

License:Apache License

private void init() {
    // the queue to support client-side surging
    outbound = new LinkedBlockingDeque<com.google.protobuf.GeneratedMessage>();

    group = new NioEventLoopGroup();
    try {//w ww .  j  av  a2 s  .com
        handler = new CommHandler();
        CommInitializer ci = new CommInitializer(handler, false);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(ci);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make the connection attempt.
        channel = b.connect(host, port).syncUninterruptibly();

        // want to monitor the connection to the server s.t. if we loose the
        // connection, we can try to re-establish it.
        ClientClosedListener ccl = new ClientClosedListener(this);
        channel.channel().closeFuture().addListener(ccl);

    } catch (Exception ex) {
        logger.error("failed to initialize the client connection", ex);

    }

    // start outbound message processor
    worker = new OutboundWorker(this);
    worker.start();
}

From source file:poke.Communication.CommunicationConnection.java

License:Apache License

private void init() {
    // the queue to support client-side surging
    //outbound = new LinkedBlockingDeque<GeneratedMessage>();

    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   w ww. j a  v a  2 s  .  co  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new CommunicationInitializer());
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make a new connection.
        channel = b.connect(host, port).sync();

        // Get the handler instance to initiate the request.
        handler = channel.channel().pipeline().get(CommunicationClientHandler.class);
        //ch.close();
        System.out.println("Connection established!!");
        ClientClosedListener ccl = new ClientClosedListener(this);
        channel.channel().closeFuture().addListener(ccl);
    } catch (Exception ex) {
        System.out.println("failed to initialize the client connection " + ex);

    }
}

From source file:poke.monitor.ElectionMonitor.java

License:Apache License

/**
 * create connection to remote server//w  ww .  j  a  v a2 s  .c o  m
 * 
 * @return
 */
public Channel connect() {
    // Start the connection attempt.
    //   while(true){
    if (channel == null) {
        try {
            //if(flag==1)
            //{
            handler = new MonitorHandler();
            MonitorInitializer mi = new MonitorInitializer(handler, false);

            Bootstrap b = new Bootstrap();
            // @TODO newFixedThreadPool(2);
            b.group(group).channel(NioSocketChannel.class).handler(mi);
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
            b.option(ChannelOption.TCP_NODELAY, true);
            b.option(ChannelOption.SO_KEEPALIVE, true);

            // Make the connection attempt.
            logger.info(host + ";" + port + "IN ELection monitor");
            channel = b.connect(host, port).syncUninterruptibly();
            channel.awaitUninterruptibly(5000l);
            channel.channel().closeFuture().addListener(new MonitorClosedListener(this));
            //flag=0;
            //Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            if (N == Integer.MAX_VALUE)
                N = 1;
            else
                N++;
            //}
            // add listeners waiting to be added
            if (listeners.size() > 0) {
                for (MonitorListener ml : listeners)
                    handler.addListener(ml);
                listeners.clear();
            }
        } catch (Exception ex) {
            logger.debug("failed to initialize the heartbeat connection");
            // logger.error("failed to initialize the heartbeat connection",
            // ex);
        }
    }

    if (channel != null && channel.isDone() && channel.isSuccess()) {

        logger.info("Channel is Created" + channel);
        return channel.channel();
    } else {
        logger.info("In Error from Establish Connection");
        throw new RuntimeException("Not able to establish connection to server");
    }

}