java.net.SocketException Java Examples

The following examples show how to use java.net.SocketException. 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: NetworkData.java    From uuid-creator with MIT License 8 votes vote down vote up
/**
 * Returns a list of {@link NetworkData}.
 * 
 * This method iterates over all the network interfaces to return those that
 * are up and running.
 * 
 * NOTE: it may be VERY EXPENSIVE on Windows systems, because that OS
 * creates a lot of virtual network interfaces.
 * 
 * @return a list of {@link NetworkData}
 */
public static List<NetworkData> getNetworkDataList() {
	try {
		InetAddress inetAddress = InetAddress.getLocalHost();
		List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

		HashSet<NetworkData> networkDataHashSet = new HashSet<>();
		for (NetworkInterface networkInterface : networkInterfaces) {
			NetworkData networkData = buildNetworkData(networkInterface, inetAddress);
			if (networkData != null) {
				networkDataHashSet.add(networkData);
			}
		}
		return new ArrayList<>(networkDataHashSet);
	} catch (SocketException | NullPointerException | UnknownHostException e) {
		return Collections.emptyList();
	}
}
 
Example #2
Source File: TcpCollectorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
@Test
public void connectFailed_withSocketException() throws Exception {
    Mockito.doThrow(new SocketException()).when(mockSocket).connect(Mockito.any());

    final TcpCollector.ConnectDatum result;
    try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) {
        result = tcpCollector.tryConnect(mockSocket);
    }

    assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.CONNECT_FAILED));
    Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress));
    Mockito.verifyNoMoreInteractions(mockSocket);
}
 
Example #3
Source File: NetworkHelper.java    From orWall with GNU General Public License v3.0 6 votes vote down vote up
public static String getMask(String intf){
    try {
        NetworkInterface ntwrk = NetworkInterface.getByName(intf);
        Iterator<InterfaceAddress> addrList = ntwrk.getInterfaceAddresses().iterator();
        while (addrList.hasNext()) {
            InterfaceAddress addr = addrList.next();
            InetAddress ip = addr.getAddress();
            if (ip instanceof Inet4Address) {
                String mask = ip.getHostAddress() + "/" +
                        addr.getNetworkPrefixLength();
                return mask;
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #4
Source File: FolderLoadThread.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load folder in a separate thread.
 *
 * @param folder       current folder
 * @param outputStream client connection
 * @throws InterruptedException on error
 * @throws IOException          on error
 */
public static void loadFolder(ExchangeSession.Folder folder, OutputStream outputStream) throws InterruptedException, IOException {
    FolderLoadThread folderLoadThread = new FolderLoadThread(currentThread().getName(), folder);
    folderLoadThread.start();
    while (!folderLoadThread.isComplete) {
        folderLoadThread.join(20000);
        LOGGER.debug("Still loading " + folder.folderPath + " (" + folder.count() + " messages)");
        if (Settings.getBooleanProperty("davmail.enableKeepAlive", false)) {
            try {
                outputStream.write(' ');
                outputStream.flush();
            } catch (SocketException e) {
                folderLoadThread.interrupt();
                throw e;
            }
        }
    }
    if (folderLoadThread.exception != null) {
        throw folderLoadThread.exception;
    }

}
 
Example #5
Source File: Util.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of all the addresses on the system.
 * @param  inclLoopback
 *         if {@code true}, include the loopback addresses
 * @param  ipv4Only
 *         it {@code true}, only IPv4 addresses will be included
 */
static List<InetAddress> getAddresses(boolean inclLoopback,
                                      boolean ipv4Only)
    throws SocketException {
    ArrayList<InetAddress> list = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> nets =
             NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netInf : Collections.list(nets)) {
        Enumeration<InetAddress> addrs = netInf.getInetAddresses();
        for (InetAddress addr : Collections.list(addrs)) {
            if (!list.contains(addr) &&
                    (inclLoopback ? true : !addr.isLoopbackAddress()) &&
                    (ipv4Only ? (addr instanceof Inet4Address) : true)) {
                list.add(addr);
            }
        }
    }

    return list;
}
 
Example #6
Source File: RemoteEndpointTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testOutputStreamClosed() throws Exception {
	LogMessageAccumulator logMessages = new LogMessageAccumulator();
	try {
		logMessages.registerTo(RemoteEndpoint.class);
		
		TestEndpoint endp = new TestEndpoint();
		MessageConsumer consumer = new MessageConsumer() {
			@Override
			public void consume(Message message) throws JsonRpcException {
				throw new JsonRpcException(new SocketException("Socket closed"));
			}
		};
		RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp);
		endpoint.notify("foo", null);
		
		logMessages.await(Level.INFO, "Failed to send notification message.");
	} finally {
		logMessages.unregister();
	}
}
 
Example #7
Source File: UDP.java    From myqq with MIT License 6 votes vote down vote up
/**
 * 获取可用的端口号
 */
public void getMyUsefulPort()
{
	while(true)
	{
   		try
   		{
   			// 实例化一个DatagramSocket
   			socket = new DatagramSocket(myPort);
   			break;
   		}
   		catch (SocketException e)
   		{
   			myPort++;
   		}
	}
}
 
Example #8
Source File: SSLSocketImpl.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Layer SSL traffic over an existing connection, rather than
 * creating a new connection.
 *
 * The existing connection may be used only for SSL traffic (using this
 * SSLSocket) until the SSLSocket.close() call returns. However, if a
 * protocol error is detected, that existing connection is automatically
 * closed.
 * <p>
 * This particular constructor always uses the socket in the
 * role of an SSL client. It may be useful in cases which start
 * using SSL after some initial data transfers, for example in some
 * SSL tunneling applications or as part of some kinds of application
 * protocols which negotiate use of a SSL based security.
 */
SSLSocketImpl(SSLContextImpl sslContext, Socket sock,
        String peerHost, int port, boolean autoClose) throws IOException {
    super(sock);
    // We always layer over a connected socket
    if (!sock.isConnected()) {
        throw new SocketException("Underlying socket is not connected");
    }

    this.sslContext = sslContext;
    HandshakeHash handshakeHash = new HandshakeHash();
    this.conContext = new TransportContext(sslContext, this,
            new SSLSocketInputRecord(handshakeHash),
            new SSLSocketOutputRecord(handshakeHash), true);
    this.peerHost = peerHost;
    this.autoClose = autoClose;
    doneConnect();
}
 
Example #9
Source File: IPUtil.java    From radar with Apache License 2.0 6 votes vote down vote up
private static String getLinuxLocalIP() {
	String ip = "";
	try {
		Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
		while (e1.hasMoreElements()) {
			NetworkInterface ni = e1.nextElement();
			if (netWorkCard.equals(ni.getName()) || NETWORK_CARD.equals(ni.getName())
					|| NETWORK_CARD_BAND.equals(ni.getName())) {
				Enumeration<InetAddress> e2 = ni.getInetAddresses();
				while (e2.hasMoreElements()) {
					InetAddress ia = e2.nextElement();
					if (ia instanceof Inet6Address) {
						continue;
					}
					ip = ia.getHostAddress();
				}
				break;
			} else {
				continue;
			}
		}
	} catch (SocketException e) {
		e.printStackTrace();
	}
	return ip;
}
 
Example #10
Source File: HostNameUtil.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
/**
 * On systems with multiple network interfaces and mixed IPv6/IPv4 get a valid network
 * interface for binding to multicast
 *
 * @return a network interface suitable for multicast
 * @throws SocketException if a problem occurs while reading the network interfaces
 */
public static NetworkInterface getMulticastNetworkInterface() throws SocketException
{
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements())
    {
        NetworkInterface networkInterface = networkInterfaces.nextElement();
        Enumeration<InetAddress> addressesFromNetworkInterface = networkInterface.getInetAddresses();
        while (addressesFromNetworkInterface.hasMoreElements())
        {
            InetAddress inetAddress = addressesFromNetworkInterface.nextElement();
            if (inetAddress.isSiteLocalAddress()
                    && !inetAddress.isAnyLocalAddress()
                    && !inetAddress.isLinkLocalAddress()
                    && !inetAddress.isLoopbackAddress()
                    && !inetAddress.isMulticastAddress())
            {
                return networkInterface;
            }
        }
    }

    return null;
}
 
Example #11
Source File: RipperServiceSocket.java    From AndroidRipper with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Send a DESCRIBE Message.
 * 
 * Call describe(MAX_RETRY = 5)
 * 
 * @return
 * @throws SocketException
 */
public String describe() throws SocketException
{
	String desc = null;
	
	try {
		desc = describe(3);
	} catch (RuntimeException rex) {
		
		if( desc == null ){
			//single retry
			desc = describe(3);
		}
		
	}
	
	return desc;
}
 
Example #12
Source File: HttpsClient.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The following method, createSocket, is defined in NetworkClient
 * and overridden here so that the socket facroty is used to create
 * new sockets.
 */
@Override
protected Socket createSocket() throws IOException {
    try {
        return sslSocketFactory.createSocket();
    } catch (SocketException se) {
        //
        // bug 6771432
        // javax.net.SocketFactory throws a SocketException with an
        // UnsupportedOperationException as its cause to indicate that
        // unconnected sockets have not been implemented.
        //
        Throwable t = se.getCause();
        if (t != null && t instanceof UnsupportedOperationException) {
            return super.createSocket();
        } else {
            throw se;
        }
    }
}
 
Example #13
Source File: WiFiUtils.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public static String getPhoneIp(Context application) {
    WifiManager wifiManager = (WifiManager) application.getSystemService("wifi");
    if (wifiManager.isWifiEnabled()) {
        return intToIp(wifiManager.getConnectionInfo().getIpAddress());
    }
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            Enumeration<InetAddress> enumIpAddr = ((NetworkInterface) en.nextElement()).getInetAddresses();
            while (enumIpAddr.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #14
Source File: AbstractTestBenchTest.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Returns host address that can be targeted from the outside, like from a
 * test hub.
 *
 * @return host address
 * @throws RuntimeException
 *             if host name could not be determined or
 *             {@link SocketException} was caught during the determination.
 */
protected String getCurrentHostAddress() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface
                .getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface nwInterface = interfaces.nextElement();
            if (!nwInterface.isUp() || nwInterface.isLoopback()
                    || nwInterface.isVirtual()) {
                continue;
            }
            Optional<String> address = getHostAddress(nwInterface);
            if (address.isPresent()) {
                return address.get();
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("Could not find the host name", e);
    }
    throw new RuntimeException(
            "No compatible (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) ip address found.");
}
 
Example #15
Source File: DatagramSocketAdaptor.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public void receive(DatagramPacket p) throws IOException {
    // get temporary direct buffer with a capacity of p.bufLength
    int bufLength = DatagramPackets.getBufLength(p);
    ByteBuffer bb = Util.getTemporaryDirectBuffer(bufLength);
    try {
        long nanos = MILLISECONDS.toNanos(timeout);
        SocketAddress sender = dc.blockingReceive(bb, nanos);
        bb.flip();
        synchronized (p) {
            // copy bytes to the DatagramPacket and set length
            int len = Math.min(bb.limit(), DatagramPackets.getBufLength(p));
            bb.get(p.getData(), p.getOffset(), len);
            DatagramPackets.setLength(p, len);

            // sender address
            p.setSocketAddress(sender);
        }
    } catch (ClosedChannelException e) {
        var exc = new SocketException("Socket closed");
        exc.initCause(e);
        throw exc;
    } finally {
        Util.offerFirstTemporaryDirectBuffer(bb);
    }
}
 
Example #16
Source File: SocketProperties.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
public void setProperties(Socket socket) throws SocketException{
    if (rxBufSize != null)
        socket.setReceiveBufferSize(rxBufSize.intValue());
    if (txBufSize != null)
        socket.setSendBufferSize(txBufSize.intValue());
    if (ooBInline !=null)
        socket.setOOBInline(ooBInline.booleanValue());
    if (soKeepAlive != null)
        socket.setKeepAlive(soKeepAlive.booleanValue());
    if (performanceConnectionTime != null && performanceLatency != null &&
            performanceBandwidth != null)
        socket.setPerformancePreferences(
                performanceConnectionTime.intValue(),
                performanceLatency.intValue(),
                performanceBandwidth.intValue());
    if (soReuseAddress != null)
        socket.setReuseAddress(soReuseAddress.booleanValue());
    if (soLingerOn != null && soLingerTime != null)
        socket.setSoLinger(soLingerOn.booleanValue(),
                soLingerTime.intValue());
    if (soTimeout != null && soTimeout.intValue() >= 0)
        socket.setSoTimeout(soTimeout.intValue());
    if (tcpNoDelay != null)
        socket.setTcpNoDelay(tcpNoDelay.booleanValue());
}
 
Example #17
Source File: ResourceSchedulerUtils.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * get ipv4 address of first matching network interface in the given list
 * network interface can not be loop back and it has to be up
 * @param interfaceNames
 * @return
 */
public static String getLocalIPFromNetworkInterfaces(List<String> interfaceNames) {

  try {
    for (String nwInterfaceName: interfaceNames) {
      NetworkInterface networkInterface = NetworkInterface.getByName(nwInterfaceName);
      if (networkInterface != null
          && !networkInterface.isLoopback()
          && networkInterface.isUp()) {
        List<InterfaceAddress> addressList = networkInterface.getInterfaceAddresses();
        for (InterfaceAddress adress: addressList) {
          if (isValidIPv4(adress.getAddress().getHostAddress())) {
            return adress.getAddress().getHostAddress();
          }
        }
      }
    }

  } catch (SocketException e) {
    LOG.log(Level.SEVERE, "Error retrieving network interface list", e);
  }

  return null;
}
 
Example #18
Source File: TransactionTransmitter.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
private boolean populateNonce() {
  try {
    transaction.updateNonce();
    return true;
  } catch (final RuntimeException e) {
    LOG.warn("Unable to get nonce from web3j provider.", e);
    final Throwable cause = e.getCause();
    if (cause instanceof SocketException
        || cause instanceof SocketTimeoutException
        || cause instanceof TimeoutException) {
      routingContext.fail(
          GATEWAY_TIMEOUT.code(), new JsonRpcException(CONNECTION_TO_DOWNSTREAM_NODE_TIMED_OUT));
    } else if (cause instanceof SSLHandshakeException) {
      routingContext.fail(BAD_GATEWAY.code(), cause);
    } else {
      routingContext.fail(GATEWAY_TIMEOUT.code(), new JsonRpcException(INTERNAL_ERROR));
    }
  } catch (final Throwable thrown) {
    LOG.debug("Failed to encode/serialize transaction: {}", transaction, thrown);
    routingContext.fail(BAD_REQUEST.code(), new JsonRpcException(INTERNAL_ERROR));
  }
  return false;
}
 
Example #19
Source File: SctpChannelImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Set<SocketAddress> getRemoteAddresses()
        throws IOException {
    synchronized (stateLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if (!isConnected() || isShutdown)
            return Collections.emptySet();

        try {
            return SctpNet.getRemoteAddresses(fdVal, 0/*unused*/);
        } catch (SocketException unused) {
            /* an open connected channel should always have remote addresses */
            return remoteAddresses;
        }
    }
}
 
Example #20
Source File: NetworkUtil.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get local Ip address.
 */
public static InetAddress getLocalIPAddress() {
    Enumeration<NetworkInterface> enumeration = null;
    try {
        enumeration = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        e.printStackTrace();
    }
    if (enumeration != null) {
        while (enumeration.hasMoreElements()) {
            NetworkInterface nif = enumeration.nextElement();
            Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
            if (inetAddresses != null) {
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress() && isIPv4Address(inetAddress.getHostAddress())) {
                        return inetAddress;
                    }
                }
            }
        }
    }
    return null;
}
 
Example #21
Source File: Local.java    From CSipSimple with GNU General Public License v3.0 6 votes vote down vote up
public String getLocalIpAddresses() {
    ArrayList<String> addresses = new ArrayList<String>();
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                    .hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    addresses.add(inetAddress.getHostAddress().toString());
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(THIS_FILE, "Impossible to get ip address", ex);
    }
    return TextUtils.join("\n", addresses);
}
 
Example #22
Source File: HttpsClient.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The following method, createSocket, is defined in NetworkClient
 * and overridden here so that the socket facroty is used to create
 * new sockets.
 */
@Override
protected Socket createSocket() throws IOException {
    try {
        return sslSocketFactory.createSocket();
    } catch (SocketException se) {
        //
        // bug 6771432
        // javax.net.SocketFactory throws a SocketException with an
        // UnsupportedOperationException as its cause to indicate that
        // unconnected sockets have not been implemented.
        //
        Throwable t = se.getCause();
        if (t != null && t instanceof UnsupportedOperationException) {
            return super.createSocket();
        } else {
            throw se;
        }
    }
}
 
Example #23
Source File: SocketFactory.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an unconnected socket.
 *
 * @return the unconnected socket
 * @throws IOException if the socket cannot be created
 * @see java.net.Socket#connect(java.net.SocketAddress)
 * @see java.net.Socket#connect(java.net.SocketAddress, int)
 * @see java.net.Socket#Socket()
 */
public Socket createSocket() throws IOException {
    //
    // bug 6771432:
    // The Exception is used by HttpsClient to signal that
    // unconnected sockets have not been implemented.
    //
    UnsupportedOperationException uop = new
            UnsupportedOperationException();
    SocketException se =  new SocketException(
            "Unconnected sockets not implemented");
    se.initCause(uop);
    throw se;
}
 
Example #24
Source File: Fix5070632.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example #25
Source File: Fix5070632.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example #26
Source File: DefaultSocketChannelConfig.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public SocketChannelConfig setReuseAddress(boolean reuseAddress) {
    try {
        javaSocket.setReuseAddress(reuseAddress);
    } catch (SocketException e) {
        throw new ChannelException(e);
    }
    return this;
}
 
Example #27
Source File: SocksIPv6Test.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean ensureInet6AddressFamily() throws IOException {
    try (ServerSocket s = new ServerSocket()) {
        s.bind(new InetSocketAddress("::1", 0));
        return true;
    } catch (SocketException e) {
        System.out.println("Inet 6 address family is not available. Skipping test suite.");
    }
    return false;
}
 
Example #28
Source File: OpenSSLSocket.java    From wildfly-openssl with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void setSoTimeout(int timeout) throws SocketException {
    if (delegate == null) {
        super.setSoTimeout(timeout);
    } else {
        delegate.setSoTimeout(timeout);
    }
}
 
Example #29
Source File: ConnectionPool.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
public synchronized Connection get(Address address) {
  Connection foundConnection = null;
  for (ListIterator<Connection> i = connections.listIterator(connections.size());
      i.hasPrevious(); ) {
    Connection connection = i.previous();
    if (!connection.getRoute().getAddress().equals(address)
        || !connection.isAlive()
        || System.nanoTime() - connection.getIdleStartTimeNs() >= keepAliveDurationNs) {
      continue;
    }
    i.remove();
    if (!connection.isSpdy()) {
      try {
        Platform.get().tagSocket(connection.getSocket());
      } catch (SocketException e) {
        Util.closeQuietly(connection);
        // When unable to tag, skip recycling and close
        Platform.get().logW("Unable to tagSocket(): " + e);
        continue;
      }
    }
    foundConnection = connection;
    break;
  }

  if (foundConnection != null && foundConnection.isSpdy()) {
    connections.addFirst(foundConnection); // Add it back after iteration.
  }

  executorService.submit(connectionsCleanupCallable);
  return foundConnection;
}
 
Example #30
Source File: UnixDomainSocketAcceptanceTest.java    From mongodb-async-driver with Apache License 2.0 5 votes vote down vote up
/**
 * Always throws a {@link SocketException}.
 */
@Override
public Socket createSocket(final InetAddress address, final int port,
        final InetAddress localAddress, final int localPort)
        throws SocketException {
    throw new SocketException(
            "AFUNIX socket does not support connections to a host/port");
}