Java Code Examples for org.jboss.netty.channel.ChannelFuture#getChannel()

The following examples show how to use org.jboss.netty.channel.ChannelFuture#getChannel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RemoteSyncManager.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
protected boolean connect(String hostname, int port) {
    ready = false;
    if (channel == null || !channel.isConnected()) {
        SocketAddress sa =
                new InetSocketAddress(hostname, port);
        ChannelFuture future = clientBootstrap.connect(sa);
        future.awaitUninterruptibly();
        if (!future.isSuccess()) {
            logger.error("Could not connect to " + hostname + 
                         ":" + port, future.getCause());
            return false;
        }
        channel = future.getChannel();
    }
    while (!ready && channel != null && channel.isConnected()) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) { }
    }
    if (!ready || channel == null || !channel.isConnected()) {
        logger.warn("Timed out connecting to {}:{}", hostname, port);
        return false;
    }
    logger.debug("Connected to {}:{}", hostname, port);
    return true;
}
 
Example 2
Source File: Connection.java    From nfs-client-java with Apache License 2.0 6 votes vote down vote up
/**
 * This attempts to bind to privileged ports, starting with 1023 and working downwards, and returns when the first binding succeeds.
 * 
 * <p>
 * Some NFS servers apparently may require that some requests originate on
 * an Internet port below IPPORT_RESERVED (1024). This is generally not
 * used, though, as the client then has to run as a user authorized for
 * privileged, which is dangerous. It is also not generally needed.
 * </p>
 * 
 * @return
 *         <ul>
 *         <li><code>true</code> if the binding succeeds,</li>
 *         <li><code>false</code> otherwise.</li>
 *         </ul>
 * @throws RpcException If an exception occurs, or if no binding succeeds.
 */
private Channel bindToPrivilegedPort() throws RpcException {
    System.out.println("Attempting to use privileged port.");
    for (int port = 1023; port > 0; --port) {
        try {
            ChannelPipeline pipeline = _clientBootstrap.getPipelineFactory().getPipeline();
            Channel channel = _clientBootstrap.getFactory().newChannel(pipeline);
            channel.getConfig().setOptions(_clientBootstrap.getOptions());
            ChannelFuture bindFuture = channel.bind(new InetSocketAddress(port)).awaitUninterruptibly();
            if (bindFuture.isSuccess()) {
                System.out.println("Success! Bound to port " + port);
                return bindFuture.getChannel();
            }
        } catch (Exception e) {
            String msg = String.format("rpc request bind error for address: %s", 
                    getRemoteAddress());
            throw new RpcException(RpcStatus.NETWORK_ERROR, msg, e);
        }
    }

    throw new RpcException(RpcStatus.LOCAL_BINDING_ERROR, String.format("Cannot bind a port < 1024: %s", getRemoteAddress()));
}
 
Example 3
Source File: Bootstrap.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
public boolean bootstrap(HostAndPort seed, 
                         Node localNode) throws SyncException {
    this.localNode = localNode;
    succeeded = false;
    SocketAddress sa =
            new InetSocketAddress(seed.getHostText(), seed.getPort());
    ChannelFuture future = bootstrap.connect(sa);
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        logger.debug("Could not connect to " + seed, future.getCause());
        return false;
    }
    Channel channel = future.getChannel();
    logger.debug("[{}] Connected to {}", 
                 localNode != null ? localNode.getNodeId() : null,
                 seed);
    
    try {
        channel.getCloseFuture().await();
    } catch (InterruptedException e) {
        logger.debug("Interrupted while waiting for bootstrap");
        return succeeded;
    }
    return succeeded;
}
 
Example 4
Source File: MongoProxyInboundHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable( false );

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap( cf );
    cb.setOption( "bufferFactory", HeapChannelBufferFactory.getInstance( ByteOrder.LITTLE_ENDIAN ) );
    cb.getPipeline().addLast( "framer", new MongoMessageFrame() );
    cb.getPipeline().addLast( "handler", new OutboundHandler( e.getChannel() ) );
    ChannelFuture f = cb.connect( new InetSocketAddress( remoteHost, remotePort ) );

    outboundChannel = f.getChannel();
    f.addListener( new ChannelFutureListener() {
        @Override
        public void operationComplete( ChannelFuture future ) throws Exception {
            if ( future.isSuccess() ) {
                // Connection attempt succeeded:
                // Begin to accept incoming traffic.
                inboundChannel.setReadable( true );
            }
            else {
                // Close the connection if the connection attempt has
                // failed.
                inboundChannel.close();
            }
        }
    } );
}
 
Example 5
Source File: NettyTransport.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
protected NodeChannels connectToChannelsLight(DiscoveryNode node) {
    InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address();
    ChannelFuture connect = clientBootstrap.connect(address);
    connect.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
    if (!connect.isSuccess()) {
        throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connect.getCause());
    }
    Channel[] channels = new Channel[1];
    channels[0] = connect.getChannel();
    channels[0].getCloseFuture().addListener(new ChannelCloseListener(node));
    return new NodeChannels(channels, channels, channels, channels, channels);
}
 
Example 6
Source File: HttpElasticsearchClient.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
    ActionEntry entry = actionMap.get(action.name());
    if (entry == null) {
        throw new IllegalStateException("no action entry for " + action.name());
    }
    HttpAction<Request, Response> httpAction = entry.httpAction;
    if (httpAction == null) {
        throw new IllegalStateException("failed to find action [" + action + "] to execute");
    }
    HttpInvocationContext<Request, Response> httpInvocationContext = new HttpInvocationContext(httpAction, listener, new LinkedList<>(), request);
    try {
        httpInvocationContext.httpRequest = httpAction.createHttpRequest(this.url, request);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort()));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        bootstrap.releaseExternalResources();
        logger.error("can't connect to {}", url);
    } else {
        Channel channel = future.getChannel();
        httpInvocationContext.setChannel(channel);
        contextMap.put(channel, httpInvocationContext);
        channel.getConfig().setConnectTimeoutMillis(settings.getAsInt("http.client.timeout", 5000));
        httpAction.execute(httpInvocationContext, listener);
    }
}
 
Example 7
Source File: HttpInvoker.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>>
        void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
    HttpElasticsearchClient.ActionEntry entry = actionMap.get(action.name());
    if (entry == null) {
        throw new IllegalStateException("no action entry for " + action.name());
    }
    HttpAction<Request, Response> httpAction = entry.httpAction;
    if (httpAction == null) {
        throw new IllegalStateException("failed to find action [" + action + "] to execute");
    }
    HttpInvocationContext<Request, Response> httpInvocationContext = new HttpInvocationContext(httpAction, listener, new LinkedList<>(), request);
    try {
        httpInvocationContext.httpRequest = httpAction.createHttpRequest(this.url, request);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort()));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        bootstrap.releaseExternalResources();
        logger.error("can't connect to {}", url);
    } else {
        Channel channel = future.getChannel();
        httpInvocationContext.setChannel(channel);
        contexts.put(channel, httpInvocationContext);
        channel.getConfig().setConnectTimeoutMillis(settings.getAsInt("http.client.timeout", 5000));
        httpAction.execute(httpInvocationContext, listener);
    }
}
 
Example 8
Source File: PinpointClientStateTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
PinpointClientHandler getSocketHandler(ChannelFuture channelConnectFuture, SocketAddress address) {
    if (address == null) {
        throw new NullPointerException("address");
    }

    Channel channel = channelConnectFuture.getChannel();
    PinpointClientHandler pinpointClientHandler = (PinpointClientHandler) channel.getPipeline().getLast();

    return pinpointClientHandler;
}
 
Example 9
Source File: TSOClientRaw.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
public TSOClientRaw(String host, int port) throws InterruptedException, ExecutionException {
    // Start client with Nb of active threads = 3 as maximum.
    ChannelFactory factory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()), 3);
    // Create the bootstrap
    ClientBootstrap bootstrap = new ClientBootstrap(factory);

    InetSocketAddress addr = new InetSocketAddress(host, port);

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder",
            new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder",
            new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());

    Handler handler = new Handler();
    pipeline.addLast("handler", handler);

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);

    ChannelFuture channelFuture = bootstrap.connect(addr).await();
    channel = channelFuture.getChannel();
}
 
Example 10
Source File: TestTSOChannelHandlerNetty.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10_000)
public void testNettyChannelWriting() throws Exception {

    // ------------------------------------------------------------------------------------------------------------
    // Prepare test
    // ------------------------------------------------------------------------------------------------------------

    // Connect channel handler
    channelHandler.reconnect();
    // Create client and connect it
    ClientBootstrap nettyClient = createNettyClientBootstrap();
    ChannelFuture channelF = nettyClient.connect(new InetSocketAddress("localhost", 1434));
    // Basic checks for connection
    while (!channelF.isDone()) /** do nothing */ ;
    assertTrue(channelF.isSuccess());
    assertTrue(channelF.getChannel().isConnected());
    Channel channel = channelF.getChannel();
    // Eventually the channel group of the server should have 2 elements
    while (channelHandler.channelGroup.size() != 2) /** do nothing */ ;
    // Write first handshake request
    TSOProto.HandshakeRequest.Builder handshake = TSOProto.HandshakeRequest.newBuilder();
    // NOTE: Add here the required handshake capabilities when necessary
    handshake.setClientCapabilities(TSOProto.Capabilities.newBuilder().build());
    channelF.getChannel().write(TSOProto.Request.newBuilder().setHandshakeRequest(handshake.build()).build());

    // ------------------------------------------------------------------------------------------------------------
    // Test channel writing
    // ------------------------------------------------------------------------------------------------------------
    testWritingTimestampRequest(channel);

    testWritingCommitRequest(channel);

    testWritingFenceRequest(channel);
}
 
Example 11
Source File: NettySend.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
public void connect(){

		bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory(
				Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool()));
		bootstrap.setOption("tcpNoDelay", false);
		bootstrap.setOption("keepAlive", true);

		final NettyClientHandler handler = new NettyClientHandler(this, timer);
		
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline =  Channels.pipeline();
				pipeline.addLast("handler", handler);
				pipeline.addLast("encoder", new StringEncoder());
				return pipeline;
			}
		});
		
		bootstrap.setOption("remoteAddress", new InetSocketAddress(host, port));
		try {
			ChannelFuture future = bootstrap.connect().sync();
			channel = future.getChannel();
		} catch (Exception e) {
			logger.error(ExceptionUtil.getErrorMessage(e));
			bootstrap.releaseExternalResources();
			System.exit(-1);//第一次连接出现异常直接退出,不走重连
		}
	}
 
Example 12
Source File: NettyTcpClientTransport.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isSuccess()) {
        onConnectFailed(future.getChannel(), future.getCause());
        return;
    }
    Channel c = future.getChannel();
    c.getCloseFuture().addListener(closeListener);
    onConnected(c);
}
 
Example 13
Source File: NettySend.java    From jlogstash-input-plugin with Apache License 2.0 4 votes vote down vote up
public void setChannel(ChannelFuture channelfuture) {
	this.channel = channelfuture.getChannel();
}
 
Example 14
Source File: NettyClient.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}
 
Example 15
Source File: NettyClient.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try {
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);

        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // Close old channel
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    } finally {
        if (!isConnected()) {
            future.cancel();
        }
    }
}
 
Example 16
Source File: NettyClient.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}
 
Example 17
Source File: NettyClient.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}
 
Example 18
Source File: NettyClient.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}
 
Example 19
Source File: NettyTransport.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected void connectToChannels(NodeChannels nodeChannels, DiscoveryNode node) {
    ChannelFuture[] connectRecovery = new ChannelFuture[nodeChannels.recovery.length];
    ChannelFuture[] connectBulk = new ChannelFuture[nodeChannels.bulk.length];
    ChannelFuture[] connectReg = new ChannelFuture[nodeChannels.reg.length];
    ChannelFuture[] connectState = new ChannelFuture[nodeChannels.state.length];
    ChannelFuture[] connectPing = new ChannelFuture[nodeChannels.ping.length];
    InetSocketAddress address = ((InetSocketTransportAddress) node.address()).address();
    for (int i = 0; i < connectRecovery.length; i++) {
        connectRecovery[i] = clientBootstrap.connect(address);
    }
    for (int i = 0; i < connectBulk.length; i++) {
        connectBulk[i] = clientBootstrap.connect(address);
    }
    for (int i = 0; i < connectReg.length; i++) {
        connectReg[i] = clientBootstrap.connect(address);
    }
    for (int i = 0; i < connectState.length; i++) {
        connectState[i] = clientBootstrap.connect(address);
    }
    for (int i = 0; i < connectPing.length; i++) {
        connectPing[i] = clientBootstrap.connect(address);
    }

    try {
        for (int i = 0; i < connectRecovery.length; i++) {
            connectRecovery[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
            if (!connectRecovery[i].isSuccess()) {
                throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectRecovery[i].getCause());
            }
            nodeChannels.recovery[i] = connectRecovery[i].getChannel();
            nodeChannels.recovery[i].getCloseFuture().addListener(new ChannelCloseListener(node));
        }

        for (int i = 0; i < connectBulk.length; i++) {
            connectBulk[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
            if (!connectBulk[i].isSuccess()) {
                throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectBulk[i].getCause());
            }
            nodeChannels.bulk[i] = connectBulk[i].getChannel();
            nodeChannels.bulk[i].getCloseFuture().addListener(new ChannelCloseListener(node));
        }

        for (int i = 0; i < connectReg.length; i++) {
            connectReg[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
            if (!connectReg[i].isSuccess()) {
                throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectReg[i].getCause());
            }
            nodeChannels.reg[i] = connectReg[i].getChannel();
            nodeChannels.reg[i].getCloseFuture().addListener(new ChannelCloseListener(node));
        }

        for (int i = 0; i < connectState.length; i++) {
            connectState[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
            if (!connectState[i].isSuccess()) {
                throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectState[i].getCause());
            }
            nodeChannels.state[i] = connectState[i].getChannel();
            nodeChannels.state[i].getCloseFuture().addListener(new ChannelCloseListener(node));
        }

        for (int i = 0; i < connectPing.length; i++) {
            connectPing[i].awaitUninterruptibly((long) (connectTimeout.millis() * 1.5));
            if (!connectPing[i].isSuccess()) {
                throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connectPing[i].getCause());
            }
            nodeChannels.ping[i] = connectPing[i].getChannel();
            nodeChannels.ping[i].getCloseFuture().addListener(new ChannelCloseListener(node));
        }

        if (nodeChannels.recovery.length == 0) {
            if (nodeChannels.bulk.length > 0) {
                nodeChannels.recovery = nodeChannels.bulk;
            } else {
                nodeChannels.recovery = nodeChannels.reg;
            }
        }
        if (nodeChannels.bulk.length == 0) {
            nodeChannels.bulk = nodeChannels.reg;
        }
    } catch (RuntimeException e) {
        // clean the futures
        List<ChannelFuture> futures = new ArrayList<>();
        futures.addAll(Arrays.asList(connectRecovery));
        futures.addAll(Arrays.asList(connectBulk));
        futures.addAll(Arrays.asList(connectReg));
        futures.addAll(Arrays.asList(connectState));
        futures.addAll(Arrays.asList(connectPing));
        for (ChannelFuture future : Collections.unmodifiableList(futures)) {
            future.cancel();
            if (future.getChannel() != null && future.getChannel().isOpen()) {
                try {
                    future.getChannel().close();
                } catch (Exception e1) {
                    // ignore
                }
            }
        }
        throw e;
    }
}
 
Example 20
Source File: NettyTcpClientTransport.java    From msgpack-rpc-java with Apache License 2.0 4 votes vote down vote up
public void operationComplete(ChannelFuture future) throws Exception {
    Channel c = future.getChannel();
    onClosed(c);
}