private Socket createSocket ( final URL pURL , final int pPort , int pConnectTimeout ) throws IOException { Socket socket ; final Object current = this ; SocketConnector connector ; Thread t = new Thread ( connector = new SocketConnector ( ) { private IOException mConnectException = null ; private Socket mLocalSocket = null ; public Socket getSocket ( ) throws IOException { if ( mConnectException != null ) { throw mConnectException ; } return mLocalSocket ; } // Run method public void run ( ) { try { mLocalSocket = new Socket ( pURL . getHost ( ) , pPort ) ; // Blocks... } catch ( IOException ioe ) { // Store this exception for later mConnectException = ioe ; } // Signal that we are done synchronized ( current ) { current . notify ( ) ; } } } ) ; t . start ( ) ; // Wait for connect synchronized ( this ) { try { /// Only wait if thread is alive! if ( t . isAlive ( ) ) { if ( pConnectTimeout > 0 ) { wait ( pConnectTimeout ) ; } else { wait ( ) ; } } } catch ( InterruptedException ie ) { // Continue excecution on interrupt? Hmmm.. } } // Throw exception if the socket didn't connect fast enough if ( ( socket = connector . getSocket ( ) ) == null ) { throw new ConnectException ( "Socket connect timed out!" ) ; } return socket ; }
Creates a socket to the given URL and port with the given connect timeout . If the socket waits more than the given timout to connect an ConnectException is thrown .