public static Socket createSocket(final SocketTask task, int timeout) throws IOException, UnknownHostException, ConnectTimeoutException { try { TimeoutController.execute(task, timeout); } catch (TimeoutController.TimeoutException e) { throw new ConnectTimeoutException( "The host did not accept the connection within timeout of " + timeout + " ms"); } Socket socket = task.getSocket(); if (task.exception != null) { throw task.exception; } return socket; }
/** * This method spawns a controller thread overseeing the process of socket * initialisation. If the socket constructor cannot be created within the specified time * limit, the controller terminates and throws an {@link ConnectTimeoutException} * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param timeout the timeout value to be used in milliseconds. If the socket cannot be * completed within the given time limit, it will be abandoned * * @return a connected Socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * */ public static Socket createSocket( final ProtocolSocketFactory socketfactory, final String host, final int port, final InetAddress localAddress, final int localPort, int timeout) throws IOException, UnknownHostException, ConnectTimeoutException { SocketTask task = new SocketTask() { public void doit() throws IOException { setSocket(socketfactory.createSocket(host, port, localAddress, localPort)); } }; try { TimeoutController.execute(task, timeout); } catch (TimeoutController.TimeoutException e) { throw new ConnectTimeoutException( "The host did not accept the connection within timeout of " + timeout + " ms"); } Socket socket = task.getSocket(); if (task.exception != null) { throw task.exception; } return socket; }