1 21 22 package org.armedbear.j; 23 24 import java.net.ConnectException ; 25 import java.net.NoRouteToHostException ; 26 import java.net.Socket ; 27 import java.net.UnknownHostException ; 28 29 public final class SocketConnection 30 { 31 private final String hostName; 32 private final int port; 33 private final int timeout; private final int checkInterval; private final Cancellable client; 36 37 private Socket socket; 38 private String errorText; 39 40 public SocketConnection(String hostName, int port, int timeout, 41 int checkInterval, Cancellable client) 42 { 43 this.hostName = hostName; 44 this.port = port; 45 this.timeout = timeout; 46 this.checkInterval = checkInterval; 47 this.client = client; 48 } 49 50 public final String getErrorText() 51 { 52 return errorText; 53 } 54 55 private final void setErrorText(String s) 56 { 57 errorText = s; 58 } 59 60 public Socket connect() 61 { 62 socket = null; 63 long start = System.currentTimeMillis(); 64 connectThread.start(); 65 while (System.currentTimeMillis() - start < timeout) { 66 try { 67 connectThread.join(checkInterval); 68 } 69 catch (InterruptedException e) { 70 Log.error(e); 71 setErrorText(e.toString()); 72 return null; 73 } 74 if (client != null && client.cancelled()) { 75 Log.debug("cancelled!"); 76 return null; 77 } 78 if (!connectThread.isAlive()) 79 break; 80 } 81 if (socket == null && connectThread.isAlive()) 82 setErrorText("Timed out"); 83 return socket; 84 } 85 86 private final Thread connectThread = new Thread ("connect") { 87 public void run() 88 { 89 try { 90 socket = new Socket (hostName, port); 91 } 92 catch (NoRouteToHostException e) { 93 setErrorText("No route to host " + hostName); 94 } 95 catch (UnknownHostException e) { 96 setErrorText("Unknown host " + hostName); 97 } 98 catch (ConnectException e) { 99 setErrorText("Connection refused"); 100 } 101 catch (Exception e) { 102 Log.error(e); 103 setErrorText("Unable to connect to " + hostName); 104 } 105 } 106 }; 107 } 108 | Popular Tags |