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

The following examples show how to use org.jboss.netty.channel.ChannelFuture#awaitUninterruptibly() . 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: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public void sendPing() {
    if (!state.isEnableCommunication()) {
        return;
    }
    logger.debug("{} sendPing() started.", objectUniqName);

    PingPayloadPacket pingPacket = new PingPayloadPacket(pingIdGenerator.incrementAndGet(), (byte) 0, state.getCurrentStateCode().getId());
    ChannelFuture future = write0(pingPacket);
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        Throwable cause = future.getCause();
        throw new PinpointSocketException("send ping failed. Error:" + cause.getMessage(), cause);
    }

    logger.debug("{} sendPing() completed.", objectUniqName);
}
 
Example 2
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 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: NettyService.java    From android-netty with Apache License 2.0 5 votes vote down vote up
/** 연결을 다시 맺어야 할 경우 connection 을 닫는다.
 */
void disconnectSessionIfItNeeds() {
	if(checkConnection() == true) {
		ChannelFuture future = mChannel.disconnect();
		future.awaitUninterruptibly();
	}
}
 
Example 5
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 6
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 7
Source File: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void sendClosedPacket(Channel channel) {
    if (!channel.isConnected()) {
        logger.debug("{} sendClosedPacket() failed. Error:channel already closed.", objectUniqName);
        return;
    }

    logger.debug("{} sendClosedPacket() started.", objectUniqName);

    ClientClosePacket clientClosePacket = new ClientClosePacket();
    ChannelFuture write = write0(clientClosePacket, sendClosePacketFailFutureListener);
    write.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);
}
 
Example 8
Source File: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void closeChannel() {
    Channel channel = this.channel;
    if (channel != null) {
        sendClosedPacket(channel);

        ChannelFuture closeFuture = channel.close();
        closeFuture.addListener(new WriteFailFutureListener(logger, "close() event failed.", "close() event success."));
        closeFuture.awaitUninterruptibly();
    }
}
 
Example 9
Source File: NettyClientFactory.java    From migration-tool with Apache License 2.0 5 votes vote down vote up
public Client createClient(String targetIP, int targetPort, int connectTimeout) throws Exception {
	ClientBootstrap bootstrap = new ClientBootstrap(nioClient);
	bootstrap.setOption("tcpNoDelay", Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")));
	bootstrap.setOption("reuseAddress", Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
	if (connectTimeout < 1000) {
		bootstrap.setOption("connectTimeoutMillis", 1000);
	} else {
		bootstrap.setOption("connectTimeoutMillis", connectTimeout);
	}
	NettyClientHandler handler = new NettyClientHandler(this);
	bootstrap.setPipelineFactory(new NettyClientPipelineFactory(handler));
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort));
	future.awaitUninterruptibly(connectTimeout);
	if (!future.isDone()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
	}
	if (future.isCancelled()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
	}
	if (!future.isSuccess()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " error", future.getCause());
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.getCause());
	}
	NettyClient client = new NettyClient(future, connectTimeout);
	handler.setClient(client);
	return client;
}
 
Example 10
Source File: NettyTransport.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public synchronized void close() {
    List<ChannelFuture> futures = new ArrayList<>();
    for (Channel channel : allChannels) {
        try {
            if (channel != null && channel.isOpen()) {
                futures.add(channel.close());
            }
        } catch (Exception e) {
            //ignore
        }
    }
    for (ChannelFuture future : futures) {
        future.awaitUninterruptibly();
    }
}
 
Example 11
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 12
Source File: NettyRpcConnection.java    From voyage with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试连接
 */
public void connect() {
       ChannelFuture future = bootstrap.connect(inetAddr);
       try{
           boolean ret = future.awaitUninterruptibly(Constants.TIMEOUT_CONNECTION_MILLSECOND, TimeUnit.MILLISECONDS);
           if (ret && future.isSuccess()) {
               Channel newChannel = future.getChannel();
               newChannel.setInterestOps(Channel.OP_READ_WRITE);
               try {
                   // 关闭旧的连接
                   Channel oldChannel = NettyRpcConnection.this.channel;
                   if (oldChannel != null) {
                       logger.info("Close old netty channel {} on create new netty channel {}", oldChannel, newChannel);
                       oldChannel.close();
                   }
               } finally {
                   if (!isConnected()) {
                       try {
                           logger.info("Close new netty channel {}, because the client closed.", newChannel);
                           newChannel.close();
                       } finally {
                       	NettyRpcConnection.this.channel = null;
                       }
                   } else {
                   	NettyRpcConnection.this.channel = newChannel;
                   }
               }
           } else if (null != future.getCause()) {
           	logger.error("connect fail", future.getCause());
           	throw new RuntimeException("connect error", future.getCause());
           } else {
           	logger.error("connect fail,connstr: "+this.getConnStr());
           	throw new RuntimeException("connect error");
           }
       }finally{
           if (! isConnected()) {
               future.cancel();
           }
       }
}
 
Example 13
Source File: InvokeFuture.java    From voyage with Apache License 2.0 5 votes vote down vote up
/**
 * 发送请求
 */
public void send() {
	ChannelFuture writeFuture = channel.write(request);
	//阻塞等待,若超时则返回已完成和失败
	boolean ret = writeFuture.awaitUninterruptibly(1000, TimeUnit.MILLISECONDS);
	if (ret && writeFuture.isSuccess()) {
		return;
	} else if(writeFuture.getCause() != null) {
		invokeMap.remove(request.getRequestID());
		throw new RpcException(writeFuture.getCause());
	} else {
		invokeMap.remove(request.getRequestID());
		throw new RpcException("sendRequest error");
	}
}
 
Example 14
Source File: NettyClient.java    From anima with GNU General Public License v3.0 4 votes vote down vote up
@Override
public 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; 
                   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 failed to connect to server "
                       + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
           } else {
               throw new RemotingException(this, "client failed to connect to server "
                       + getRemoteAddress() + " client-side timeout "
                       + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client");
           }
       }finally{
           if (! isConnected()) {
               future.cancel();
           }
       }
}
 
Example 15
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 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: OspfInterfaceImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    if (channel != null && channel.isOpen() && channel.isConnected()) {
        if (interfaceType() == OspfInterfaceType.BROADCAST.value()) {
            if (interfaceTypeOldValue != interfaceType()) {
                try {
                    callDrElection(channel);
                } catch (Exception e) {
                    log.debug("Error while calling interfaceUp {}", e.getMessage());
                }
            }
        } else {
            if (interfaceTypeOldValue != interfaceType()) {
                interfaceTypeOldValue = interfaceType();
            }
        }
        HelloPacket hellopacket = new HelloPacket();
        //Headers
        hellopacket.setOspfVer(OspfUtil.OSPF_VERSION);
        hellopacket.setOspftype(OspfPacketType.HELLO.value());
        hellopacket.setOspfPacLength(0); //will be modified while encoding
        hellopacket.setRouterId(ospfArea.routerId());
        hellopacket.setAreaId(ospfArea.areaId());
        hellopacket.setChecksum(0); //will be modified while encoding
        hellopacket.setAuthType(OspfUtil.NOT_ASSIGNED);
        hellopacket.setAuthentication(OspfUtil.NOT_ASSIGNED);
        //Body
        hellopacket.setNetworkMask(ipNetworkMask());
        hellopacket.setOptions(ospfArea.options());
        hellopacket.setHelloInterval(helloIntervalTime());
        hellopacket.setRouterPriority(routerPriority());
        hellopacket.setRouterDeadInterval(routerDeadIntervalTime());
        hellopacket.setDr(dr());
        hellopacket.setBdr(bdr());

        Map<String, OspfNbr> listOfNeighbors = listOfNeighbors();
        Set<String> keys = listOfNeighbors.keySet();
        Iterator itr = keys.iterator();
        while (itr.hasNext()) {
            String nbrKey = (String) itr.next();
            OspfNbrImpl nbr = (OspfNbrImpl) listOfNeighbors.get(nbrKey);
            if (nbr.getState() != OspfNeighborState.DOWN) {
                hellopacket.addNeighbor(Ip4Address.valueOf(nbrKey));
            }
        }
        // build a hello Packet
        if (channel == null || !channel.isOpen() || !channel.isConnected()) {
            log.debug("Hello Packet not sent !!.. Channel Issue...");
            return;
        }

        hellopacket.setDestinationIp(OspfUtil.ALL_SPF_ROUTERS);
        byte[] messageToWrite = getMessage(hellopacket);
        ChannelFuture future = channel.write(messageToWrite);
        if (future.isSuccess()) {
            log.debug("Hello Packet successfully sent !!");
        } else {
            future.awaitUninterruptibly();
        }

    }
}
 
Example 20
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();
        }
    }
}