1 package net.matuschek.util; 2 3 import java.io.IOException ; 4 import java.io.InterruptedIOException ; 5 import java.net.InetAddress ; 6 import java.net.Socket ; 7 8 19 public class TimedSocket 20 { 21 22 30 public static Socket getSocket ( InetAddress addr, int port, int delay) 31 throws InterruptedIOException , IOException 32 { 33 SocketThread st = new SocketThread( addr, port ); 35 st.start(); 36 37 int timer = 0; 38 Socket sock = null; 39 40 for (;;) { 41 43 if (st.isConnected()) { 44 sock = st.getSocket(); 46 break; 47 } else { 48 if (st.isError()) { 50 throw (st.getException()); 52 } 53 54 try { 55 Thread.sleep ( POLL_DELAY ); 57 } catch (InterruptedException ie) {} 58 59 timer += POLL_DELAY; 61 62 if (timer > delay) { 64 throw new InterruptedIOException ("Could not connect for " + 66 delay + " milliseconds"); 67 } 68 } 69 } 70 71 return sock; 72 } 73 74 82 public static Socket getSocket ( String host, int port, int delay) 83 throws InterruptedIOException , IOException 84 { 85 InetAddress inetAddr = InetAddress.getByName (host); 87 88 return getSocket ( inetAddr, port, delay ); 89 } 90 91 92 96 static class SocketThread extends Thread 97 { 98 volatile private Socket m_connection = null; 100 private String m_host = null; 102 private InetAddress m_inet = null; 104 private int m_port = 0; 106 private IOException m_exception = null; 108 109 public SocketThread ( String host, int port) { 111 m_host = host; 113 m_port = port; 114 } 115 116 public SocketThread ( InetAddress inetAddr, int port ) { 118 m_inet = inetAddr; 120 m_port = port; 121 } 122 123 public void run() { 124 Socket sock = null; 126 127 try { 128 if (m_host != null) { 130 sock = new Socket (m_host, m_port); 132 } else { 133 sock = new Socket (m_inet, m_port); 135 } 136 } 137 catch (IOException ioe) { 138 m_exception = ioe; 140 return; 141 } 142 143 m_connection = sock; 146 } 147 148 public boolean isConnected() { 150 if (m_connection == null) 151 return false; 152 else 153 return true; 154 } 155 156 public boolean isError() { 158 if (m_exception == null) 159 return false; 160 else 161 return true; 162 } 163 164 public Socket getSocket() { 166 return m_connection; 167 } 168 169 public IOException getException() { 171 return m_exception; 172 } 173 } 174 175 176 private static final int POLL_DELAY = 100; 177 } 178 | Popular Tags |