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.kurento.jsonrpc.client.JsonRpcClientNettyWebSocket.java

License:Apache License

@Override
protected void connectNativeClient() throws TimeoutException, Exception {

    if (channel == null || !channel.isActive() || group == null || group.isShuttingDown()
            || group.isShutdown()) {/*from w  w w .  j  a  va2s.  c  o  m*/

        log.info("{} Connecting native client", label);

        final boolean ssl = "wss".equalsIgnoreCase(this.uri.getScheme());
        final SslContext sslCtx;
        try {
            sslCtx = ssl
                    ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()
                    : null;
        } catch (SSLException e) {
            log.error("{} Could not create SSL Context", label, e);
            throw new IllegalArgumentException("Could not create SSL context. See logs for more details", e);
        }

        final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final int port;
        if (uri.getPort() == -1) {
            if ("ws".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("wss".equalsIgnoreCase(scheme)) {
                port = 443;
            } else {
                port = -1;
            }
        } else {
            port = uri.getPort();
        }

        if (group == null || group.isShuttingDown() || group.isShutdown() || group.isTerminated()) {
            log.info("{} Creating new NioEventLoopGroup", label);
            group = new NioEventLoopGroup();
        }

        if (channel != null) {
            log.info("{} Closing previously existing channel when connecting native client", label);
            closeChannel();
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                log.info("{} Inititating new Netty channel. Will create new handler too!", label);
                handler = new JsonRpcWebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
                        WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), maxPacketSize));

                ChannelPipeline p = ch.pipeline();
                p.addLast("idleStateHandler", new IdleStateHandler(0, 0, idleTimeout / 1000));
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                        WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        }).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.connectionTimeout);

        int numRetries = 0;
        final int maxRetries = 5;
        while (channel == null || !channel.isOpen()) {
            try {
                channel = b.connect(host, port).sync().channel();
                handler.handshakeFuture().sync();
            } catch (InterruptedException e) {
                // This should never happen
                log.warn("{} ERROR connecting WS Netty client, opening channel", label, e);
            } catch (Exception e) {
                if (e.getCause() instanceof WebSocketHandshakeException && numRetries < maxRetries) {
                    log.warn(
                            "{} Upgrade exception when trying to connect to {}. Try {} of {}. Retrying in 200ms ",
                            label, uri, numRetries + 1, maxRetries);
                    Thread.sleep(200);
                    numRetries++;
                } else {
                    throw e;
                }
            }

        }

        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("{} channel closed", label);
                handleReconnectDisconnection(1001, "Channel closed");
            }
        });

    }

}

From source file:org.marketcetera.client.rpc.RpcClientImpl.java

@Override
protected void connectWebServices() throws I18NException, RemoteException {
    SLF4JLoggerProxy.debug(this, "Connecting to RPC server at {}:{}", mParameters.getHostname(),
            mParameters.getPort());/*  ww  w.  j  a v a 2s . c o  m*/
    PeerInfo server = new PeerInfo(mParameters.getHostname(), mParameters.getPort());
    DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
    executor = new ThreadPoolCallExecutor(1, 10);
    clientFactory.setRpcServerCallExecutor(executor);
    clientFactory.setConnectResponseTimeoutMillis(10000);
    clientFactory.setCompression(true);
    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);
    try {
        channel = clientFactory.peerWith(server, bootstrap);
        clientService = RpcClientService.newBlockingStub(channel);
        controller = channel.newRpcController();
        java.util.Locale currentLocale = java.util.Locale.getDefault();
        LoginRequest loginRequest = LoginRequest.newBuilder().setAppId(ClientVersion.APP_ID.getValue())
                .setVersionId(ClientVersion.APP_ID_VERSION.getVersionInfo())
                .setClientId(NodeId.generate().getValue())
                .setLocale(Locale.newBuilder()
                        .setCountry(currentLocale.getCountry() == null ? "" : currentLocale.getCountry())
                        .setLanguage(currentLocale.getLanguage() == null ? "" : currentLocale.getLanguage())
                        .setVariant(currentLocale.getVariant() == null ? "" : currentLocale.getVariant())
                        .build())
                .setUsername(mParameters.getUsername()).setPassword(new String(mParameters.getPassword()))
                .build();
        LoginResponse loginResponse = clientService.login(controller, loginRequest);
        sessionId = new SessionId(loginResponse.getSessionId());
    } catch (IOException | ServiceException e) {
        throw new RemoteException(e);
    }
}

From source file:org.marketcetera.marketdata.core.rpc.MarketDataRpcClient.java

/**
 * Starts the remote service./*from  w  ww.  ja  v a2 s.c o m*/
 *
 * @throws IOException if an error occurs starting the service
 * @throws ServiceException if an error occurs starting the service
 */
private void startService() throws IOException, ServiceException {
    try (CloseableLock startLock = CloseableLock.create(serviceLock.writeLock())) {
        startLock.lock();
        SLF4JLoggerProxy.debug(this, "Connecting to RPC server at {}:{}", //$NON-NLS-1$
                hostname, port);
        PeerInfo server = new PeerInfo(hostname, port);
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        executor = new ThreadPoolCallExecutor(1, 10);
        clientFactory.setRpcServerCallExecutor(executor);
        clientFactory.setConnectResponseTimeoutMillis(10000);
        clientFactory.setCompression(true);
        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);
        channel = clientFactory.peerWith(server, bootstrap);
        clientService = RpcMarketDataService.newBlockingStub(channel);
        controller = channel.newRpcController();
        java.util.Locale currentLocale = java.util.Locale.getDefault();
        LoginRequest loginRequest = LoginRequest.newBuilder().setAppId(APP_ID.getValue())
                .setVersionId(APP_ID_VERSION.getVersionInfo()).setClientId(NodeId.generate().getValue())
                .setLocale(Locale.newBuilder()
                        .setCountry(currentLocale.getCountry() == null ? "" : currentLocale.getCountry()) //$NON-NLS-1$
                        .setLanguage(currentLocale.getLanguage() == null ? "" : currentLocale.getLanguage()) //$NON-NLS-1$
                        .setVariant(currentLocale.getVariant() == null ? "" : currentLocale.getVariant()) //$NON-NLS-1$
                        .build()).setUsername(username).setPassword(new String(password)).build();
        LoginResponse loginResponse = clientService.login(controller, loginRequest);
        sessionId = new SessionId(loginResponse.getSessionId());
        setServerStatus(true);
    }
}

From source file:org.marketcetera.saclient.rpc.RpcSAClientImpl.java

/**
 * Starts the remote service.//from  w  w  w .ja va 2 s  .  c  o m
 *
 * @throws IOException if an error occurs starting the service
 * @throws ServiceException if an error occurs starting the service
 */
private void startService() throws IOException, ServiceException {
    try (CloseableLock startLock = CloseableLock.create(serviceLock.writeLock())) {
        startLock.lock();
        SLF4JLoggerProxy.debug(this, "Connecting to RPC server at {}:{}", //$NON-NLS-1$
                parameters.getHostname(), parameters.getPort());
        PeerInfo server = new PeerInfo(parameters.getHostname(), parameters.getPort());
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        executor = new ThreadPoolCallExecutor(1, 10);
        clientFactory.setRpcServerCallExecutor(executor);
        clientFactory.setConnectResponseTimeoutMillis(10000);
        clientFactory.setCompression(true);
        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);
        channel = clientFactory.peerWith(server, bootstrap);
        clientService = RpcSAClientService.newBlockingStub(channel);
        controller = channel.newRpcController();
        java.util.Locale currentLocale = java.util.Locale.getDefault();
        LoginRequest loginRequest = LoginRequest.newBuilder().setAppId(SAClientVersion.APP_ID.getValue())
                .setVersionId(SAClientVersion.APP_ID_VERSION.getVersionInfo())
                .setClientId(NodeId.generate().getValue())
                .setLocale(Locale.newBuilder()
                        .setCountry(currentLocale.getCountry() == null ? "" : currentLocale.getCountry()) //$NON-NLS-1$
                        .setLanguage(currentLocale.getLanguage() == null ? "" : currentLocale.getLanguage()) //$NON-NLS-1$
                        .setVariant(currentLocale.getVariant() == null ? "" : currentLocale.getVariant()) //$NON-NLS-1$
                        .build()).setUsername(parameters.getUsername()).setPassword(new String(parameters.getPassword()))
                .build();
        LoginResponse loginResponse = clientService.login(controller, loginRequest);
        sessionId = new SessionId(loginResponse.getSessionId());
        connectionStatusChanged(isRunning(), true);
    }
}

From source file:org.msgpack.rpc.impl.netty.NettyTcpClientTransport.java

License:Apache License

NettyTcpClientTransport(final TcpClientConfig config, final Session session, final NettyEventLoop loop) {
    // TODO check session.getAddress() instanceof IPAddress
    final RpcMessageHandler handler = new RpcMessageHandler(session);

    _bootstrap = new Bootstrap().group(new NioEventLoopGroup(/*2*/)).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.round((float) config.getConnectTimeout()))
            .option(ChannelOption.TCP_NODELAY,
                    !Boolean.FALSE.equals(config.getOption(ChannelOption.TCP_NODELAY.name())))
            .option(ChannelOption.SO_KEEPALIVE,
                    !Boolean.FALSE.equals(config.getOption(ChannelOption.SO_KEEPALIVE.name())))
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from w  ww. j  ava2  s  .  c om
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new MessagePackDecoder(loop.getObjectMapper()),
                            new MessageHandler(handler), new MessagePackEncoder(loop.getObjectMapper()));
                }
            });

    _session = session;
    _writables = new ConcurrentLinkedQueue<>();
}

From source file:org.msrpenabler.server.net.NioMsrpSockClientBootStrap.java

License:Apache License

public ChannelFuture connect(InetAddress addr, int port, int connectTOms) {

    // Start the client.
    bootClt.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTOms);

    SocketAddress remoteSockAddr = new InetSocketAddress(addr, port);
    SocketAddress localSockAddr = new InetSocketAddress(addrLocalServ.inetAddr, 0);

    return bootClt.connect(remoteSockAddr, localSockAddr);
    //return bootClt.connect(addr, port);
}

From source file:org.opendaylight.protocol.bgp.rib.impl.protocol.BGPProtocolSessionPromise.java

License:Open Source License

public synchronized void connect() {
    final BGPProtocolSessionPromise lock = this;

    try {/*w w  w .  jav a  2  s .  c  o  m*/
        LOG.debug("Promise {} attempting connect for {}ms", lock, Integer.valueOf(CONNECT_TIMEOUT));
        if (this.address.isUnresolved()) {
            this.address = new InetSocketAddress(this.address.getHostName(), this.address.getPort());
        }

        this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
        this.bootstrap.remoteAddress(this.address);
        final ChannelFuture connectFuture = this.bootstrap.connect();
        connectFuture.addListener(new BGPProtocolSessionPromise.BootstrapConnectListener(lock));
        this.pending = connectFuture;
    } catch (Exception e) {
        LOG.info("Failed to connect to {}", this.address, e);
        this.setFailure(e);
    }
}

From source file:org.opendaylight.protocol.bmp.impl.BmpDispatcherImpl.java

License:Open Source License

@Override
public ChannelFuture createClient(final InetSocketAddress address, final BmpSessionListenerFactory slf,
        final Optional<KeyMapping> keys) {

    final Bootstrap b = new Bootstrap();

    Preconditions.checkNotNull(address);

    if (Epoll.isAvailable()) {
        b.channel(EpollSocketChannel.class);
    } else {/*from w  w w .  j a  v a  2  s.co m*/
        b.channel(NioSocketChannel.class);
    }
    if (keys.isPresent()) {
        if (Epoll.isAvailable()) {
            b.option(EpollChannelOption.TCP_MD5SIG, keys.get());
        } else {
            throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
        }
    }
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
    b.group(this.workerGroup);

    b.handler(new ChannelInitializer<AbstractChannel>() {
        @Override
        protected void initChannel(final AbstractChannel ch) throws Exception {
            ch.pipeline().addLast(BmpDispatcherImpl.this.hf.getDecoders());
            ch.pipeline().addLast(BmpDispatcherImpl.this.sessionFactory.getSession(ch, slf));
        }
    });

    b.remoteAddress(address);
    final ChannelFuture channelPromise = b.connect();
    channelPromise.addListener(new BmpDispatcherImpl.BootstrapListener(b, address));
    return channelPromise;
}

From source file:org.opendaylight.protocol.bmp.mock.BmpMockDispatcher.java

License:Open Source License

private Bootstrap createClientInstance(final SocketAddress localAddress) {
    final NioEventLoopGroup workergroup = new NioEventLoopGroup();
    final Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.group(workergroup);/* w  w w.  j  a  v a  2s.c om*/

    bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(BmpMockDispatcher.this.sessionFactory.getSession(ch, null));
            ch.pipeline().addLast(BmpMockDispatcher.this.hf.getEncoders());
        }
    });
    bootstrap.localAddress(localAddress);
    return bootstrap;
}

From source file:org.opendaylight.protocol.framework.ProtocolSessionPromise.java

License:Open Source License

synchronized void connect() {
    final Object lock = this;

    try {//from   w ww . j  av  a  2  s . co m
        final int timeout = this.strategy.getConnectTimeout();

        LOG.debug("Promise {} attempting connect for {}ms", lock, timeout);

        if (this.address.isUnresolved()) {
            this.address = new InetSocketAddress(this.address.getHostName(), this.address.getPort());
        }
        this.b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
        final ChannelFuture connectFuture = this.b.connect(this.address);
        // Add listener that attempts reconnect by invoking this method again.
        connectFuture.addListener(new BootstrapConnectListener(lock));
        this.pending = connectFuture;
    } catch (final Exception e) {
        LOG.info("Failed to connect to {}", address, e);
        setFailure(e);
    }
}