java.net.ConnectException类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(81)

本文整理了Java中java.net.ConnectException类的一些代码示例,展示了ConnectException类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ConnectException类的具体详情如下:
包路径:java.net.ConnectException
类名称:ConnectException

ConnectException介绍

[英]A ConnectException is thrown if a connection cannot be established to a remote host on a specific port.

Most applications should not catch this exception; it is more robust to catch the superclass SocketException.
[中]如果无法在特定端口上建立到远程主机的连接,将引发ConnectException。
大多数应用程序不应捕获此异常;捕获超类SocketException更加健壮。

代码示例

代码示例来源:origin: apache/geode

this.preserveOrder = preserveOrder;
setRemoteAddr(remoteAddr);
this.conduitIdStr = this.owner.getConduit().getSocketId().toString();
this.handshakeRead = false;
this.handshakeCancelled = false;
  new InetSocketAddress(remoteAddr.getInetAddress(), remoteAddr.getDirectChannelPort());
SocketChannel channel = SocketChannel.open();
this.owner.addConnectingSocket(channel.socket(), addr.getAddress());
 channel.socket().setTcpNoDelay(true);
 channel.socket().setKeepAlive(SocketCreator.ENABLE_TCP_KEEP_ALIVE);
  channel.socket().connect(addr, connectTime);
  ConnectException c = new ConnectException("Encountered bug #45044 - retrying");
  c.initCause(e);
  ConnectException c = new ConnectException("Problem connecting to peer " + addr);
  c.initCause(e);
  throw c;
 } catch (CancelledKeyException | ClosedSelectorException e) {
  ConnectException c = new ConnectException(
    String.format("Attempt timed out after %s milliseconds",
      connectTime));
  c.initCause(e);
  throw c;

代码示例来源:origin: apache/zeppelin

public static boolean checkIfRemoteEndpointAccessible(String host, int port) {
 try {
  Socket discover = new Socket();
  discover.setSoTimeout(1000);
  discover.connect(new InetSocketAddress(host, port), 1000);
  discover.close();
  return true;
 } catch (ConnectException cne) {
  // end point is not accessible
  if (LOGGER.isDebugEnabled()) {
   LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible " +
     "(might be initializing): " + cne.getMessage());
  }
  return false;
 } catch (IOException ioe) {
  // end point is not accessible
  if (LOGGER.isDebugEnabled()) {
   LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible " +
     "(might be initializing): " + ioe.getMessage());
  }
  return false;
 }
}

代码示例来源:origin: io.netty/netty

private static void connect(SelectionKey k) throws IOException {
  NioClientSocketChannel ch = (NioClientSocketChannel) k.attachment();
  try {
    if (ch.channel.finishConnect()) {
      k.cancel();
      if (ch.timoutTimer != null) {
        ch.timoutTimer.cancel();
      }
      ch.worker.register(ch, ch.connectFuture);
    }
  } catch (ConnectException e) {
    ConnectException newE = new ConnectException(e.getMessage() + ": " + ch.requestedRemoteAddress);
    newE.setStackTrace(e.getStackTrace());
    throw newE;
  }
}

代码示例来源:origin: netty/netty

AnnotatedConnectException(ConnectException exception, SocketAddress remoteAddress) {
  super(exception.getMessage() + ": " + remoteAddress);
  initCause(exception);
  setStackTrace(exception.getStackTrace());
}

代码示例来源:origin: redisson/redisson

final boolean failConnectPromise(Throwable cause) {
  if (connectPromise != null) {
    // SO_ERROR has been shown to return 0 on macOS if detect an error via read() and the write filter was
    // not set before calling connect. This means finishConnect will not detect any error and would
    // successfully complete the connectPromise and update the channel state to active (which is incorrect).
    ChannelPromise connectPromise = AbstractKQueueChannel.this.connectPromise;
    AbstractKQueueChannel.this.connectPromise = null;
    if (connectPromise.tryFailure((cause instanceof ConnectException) ? cause
            : new ConnectException("failed to connect").initCause(cause))) {
      closeIfClosed();
      return true;
    }
  }
  return false;
}

代码示例来源:origin: k9mail/k-9

private void handleConnectException(ConnectException e) throws ConnectException {
  String message = e.getMessage();
  String[] tokens = message.split("-");
  if (tokens.length > 1 && tokens[1] != null) {
    Timber.e(e, "Stripping host/port from ConnectionException for %s", getLogId());
    throw new ConnectException(tokens[1].trim());
  } else {
    throw e;
  }
}

代码示例来源:origin: jmxtrans/jmxtrans-agent

private void ensureGraphiteConnection() throws IOException {
  boolean socketIsValid;
  try {
    socketIsValid = socket != null &&
        socket.isConnected()
        && socket.isBound()
        && !socket.isClosed()
        && !socket.isInputShutdown()
        && !socket.isOutputShutdown();
  } catch (Exception e) {
    socketIsValid = false;
  }
  if (!socketIsValid) {
    writer = null;
    try {
      socket = new Socket();
      socket.setKeepAlive(true);
      socket.connect(
          new InetSocketAddress(graphiteServerHostAndPort.getHost(), graphiteServerHostAndPort.getPort()),
          socketConnectTimeoutInMillis);
    } catch (IOException e) {
      ConnectException ce = new ConnectException("Exception connecting to " + graphiteServerHostAndPort);
      ce.initCause(e);
      throw ce;
    }
  }
  if (writer == null) {
    writer = new OutputStreamWriter(socket.getOutputStream(), UTF_8);
  }
}

代码示例来源:origin: org.jppf/jppf-common

/**
 * Open the underlying socket connection.
 * @throws ConnectException if the socket fails to connect.
 * @throws IOException if the underlying input and output streams raise an error.
 */
@Override
public final void open() throws ConnectException, IOException {
 if (!opened) {
  if ((host == null) || "".equals(host.trim())) throw new ConnectException("You must specify the host name");
  else if (port <= 0) throw new ConnectException("You must specify the port number");
  socket = new Socket();
  final InetSocketAddress addr = new InetSocketAddress(host, port);
  socket.setReceiveBufferSize(IO.SOCKET_BUFFER_SIZE);
  socket.setSendBufferSize(IO.SOCKET_BUFFER_SIZE);
  socket.setTcpNoDelay(IO.SOCKET_TCP_NODELAY);
  socket.setKeepAlive(IO.SOCKET_KEEPALIVE);
  socket.connect(addr);
  initStreams();
  opened = true;
  if (log.isDebugEnabled()) log.debug("getReceiveBufferSize() = " + socket.getReceiveBufferSize());
 }
 //else throw new ConnectException("Client connection already opened");
}

代码示例来源:origin: OpenNMS/opennms

m_socket = new Socket();
  m_socket.setTcpNoDelay(true);
  m_socket.connect(new InetSocketAddress(getAddress(), getPort()), getTimeout());
  m_socket.setSoTimeout(getTimeout());
  disconnect();
} catch (final ConnectException e) {
  LOG.debug("connection failed: {}", e.getMessage());
  setError(e);
  disconnect();

代码示例来源:origin: org.apache.hadoop/hadoop-common-test

socket.bind(new InetSocketAddress("127.0.0.1", 0));
System.err.println("local address: " + socket.getLocalAddress());
System.err.println("local port: " + socket.getLocalPort());
try {
 NetUtils.connect(socket,
  new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()),
  20000);
 socket.close();
} catch (ConnectException ce) {
 System.err.println("Got exception: " + ce);
 assertTrue(ce.getMessage().contains("resulted in a loopback"));
} catch (SocketException se) {

代码示例来源:origin: com.sun.mail/javax.mail

host + ":" + port);
if (cto >= 0)
  socket.connect(new InetSocketAddress(proxyHost, proxyPort), cto);
else
  socket.connect(new InetSocketAddress(proxyHost, proxyPort));
PrintStream os = new PrintStream(socket.getOutputStream(), false,
          StandardCharsets.UTF_8.name());
StringBuilder requestBuilder = new StringBuilder();
    ConnectException ex = new ConnectException(
    "connection through proxy " +
    proxyHost + ":" + proxyPort + " to " +

代码示例来源:origin: net.sf.jdos/jdos-client

public static ArrayList<Service> getServices(InetAddress host,int port, String serviceGroup) throws ConnectException {
  ArrayList<Service>  result=new ArrayList<Service> ();
  Socket s=createSocket(host, port, 5, 1000);
  if (s==null) throw new ConnectException("Could not connect to host "+host+" at port "+ port);
  BufferedReader is;
  try {
    is = new BufferedReader(new InputStreamReader(s.getInputStream()));
    BufferedWriter os=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));		
    os.write(new QueryGroupServicesImpl(serviceGroup).toString()+"\n");	
    String lineread=null;
    do {
      lineread=is.readLine();
      if (lineread!=null && !lineread.isEmpty()){
        Service serv=ServiceImpl.fromString(lineread);
        result.add(serv);               
      }
    } while (lineread!=null && !lineread.isEmpty());
    s.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
  Logger.getLogger(RemoteSocketClient.class.getName()).log(Level.SEVERE, null, "finished  queryallservices");
  return result;
}

代码示例来源:origin: org.jitsi/jain-sip-ri-ossonly

public Socket createSocket(InetAddress address, int port,
    InetAddress myAddress) throws IOException {
  if (myAddress != null) {
    Socket sock = new Socket();
    // http://java.net/jira/browse/JSIP-440 trying to bind to the correct ipaddress (in case of multiple vip addresses by example)
    // and let the JDK pick an ephemeral port
    sock.bind(new InetSocketAddress(myAddress, 0));
    try {
      sock.connect(new InetSocketAddress(address, port), 8000);
    } catch (SocketTimeoutException e) {
      throw new ConnectException("Socket timeout error (8sec)" + address + ":" + port);
    }
    return sock;
  }
  else {
    Socket sock =  new Socket();
    try {
      sock.connect(new InetSocketAddress(address, port), 8000);
    } catch (SocketTimeoutException e) {
      throw new ConnectException("Socket timeout error (8sec)" + address + ":" + port);
    }
    return sock;
  }
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

SocketChannel ch = socket.getChannel();
   "Local address %s must be of same family as remote address %s.",
   localAddr, endpoint);
 socket.bind(localAddr);
 if (ch == null) {
  socket.connect(endpoint, timeout);
 } else {
  SocketIOWithTimeout.connect(ch, endpoint, timeout);
 LOG.info("Detected a loopback TCP socket, disconnecting it");
 socket.close();
 throw new ConnectException(
  "Localhost targeted connection resulted in a loopback. " +
  "No daemon is listening on the target port.");

代码示例来源:origin: org.sonatype.sisu/sisu-jsw-utils

private void ping()
{
  try
  {
    log.debug( "Pinging on port {} ...", port );
    socket = new Socket();
    socket.connect( new InetSocketAddress( LOCALHOST, port ), timeout );
  }
  catch ( ConnectException e )
  {
    // TODO this check is quite a hack. we need a better way to determine that connection was refused
    if ( "Connection refused".equals( e.getMessage() ) )
    {
      running = false;
      shutdownJSW();
    }
  }
  catch ( IOException e )
  {
    // log.debug( "Skipped {}:{}", e.getClass().getName(), e.getMessage() );
  }
  finally
  {
    close( socket );
  }
}

代码示例来源:origin: stackoverflow.com

socketConnection = null;

for(InetAddress addr : InetAddress.getAllByName(server))
{
  if (addr instanceof Inet4Address)
  {
    socketConnection = new Socket();
    try {
      socketConnection.connect(new InetSocketAddress(addr, port));
      break;
    }
    catch (IOException e) {
      socketConnection = null;
    }
  }
}

if (socketConnection == null) {
  throw new ConnectException("Cannot connect to '" + host + "' using IPv4");
}

代码示例来源:origin: square/okhttp

/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout, Call call,
  EventListener eventListener) throws IOException {
 Proxy proxy = route.proxy();
 Address address = route.address();
 rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
   ? address.socketFactory().createSocket()
   : new Socket(proxy);
 eventListener.connectStart(call, route.socketAddress(), proxy);
 rawSocket.setSoTimeout(readTimeout);
 try {
  Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
 } catch (ConnectException e) {
  ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
  ce.initCause(e);
  throw ce;
 }
 // The following try/catch block is a pseudo hacky way to get around a crash on Android 7.0
 // More details:
 // https://github.com/square/okhttp/issues/3245
 // https://android-review.googlesource.com/#/c/271775/
 try {
  source = Okio.buffer(Okio.source(rawSocket));
  sink = Okio.buffer(Okio.sink(rawSocket));
 } catch (NullPointerException npe) {
  if (NPE_THROW_WITH_NULL.equals(npe.getMessage())) {
   throw new IOException(npe);
  }
 }
}

代码示例来源:origin: io.netty/netty

channel.socket.connect(
    remoteAddress, channel.getConfig().getConnectTimeoutMillis());
connected = true;
channel.in = new PushbackInputStream(channel.socket.getInputStream(), 1);
channel.out = channel.socket.getOutputStream();
if (t instanceof ConnectException) {
  if (t instanceof ConnectException) {
    Throwable newT = new ConnectException(t.getMessage() + ": " + remoteAddress);
    newT.setStackTrace(t.getStackTrace());
    t = newT;

代码示例来源:origin: org.gradle/gradle-messaging

private SocketChannel tryConnect(InetEndpoint address, InetAddress candidate) throws IOException {
  SocketChannel socketChannel = SocketChannel.open();
  try {
    socketChannel.socket().connect(new InetSocketAddress(candidate, address.getPort()), CONNECT_TIMEOUT);
    if (!detectSelfConnect(socketChannel)) {
      return socketChannel;
    }
    socketChannel.close();
  } catch (IOException e) {
    socketChannel.close();
    throw e;
  } catch (Throwable e) {
    socketChannel.close();
    throw UncheckedException.throwAsUncheckedException(e);
  }
  throw new java.net.ConnectException(String.format("Socket connected to itself on %s port %s.", candidate, address.getPort()));
}

代码示例来源:origin: timewalker74/ffmq

socket.connect(new InetSocketAddress(host,port),connectTimeout*1000);
log.error("#"+id+" could not connect to "+host+":"+port+" (timeout="+connectTimeout+"s) : "+e.getMessage());
throw new PacketTransportException("Could not connect to "+host+":"+port+" : "+e.toString());

相关文章