01: /*
02: * SocketConnection.java
03: *
04: * Copyright (C) 2002 Peter Graves
05: * $Id: SocketConnection.java,v 1.1.1.1 2002/09/24 16:07:54 piso Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
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: private final String hostName;
31: private final int port;
32: private final int timeout; // milliseconds
33: private final int checkInterval; // milliseconds
34: private final Cancellable client;
35:
36: private Socket socket;
37: private String errorText;
38:
39: public SocketConnection(String hostName, int port, int timeout,
40: int checkInterval, Cancellable client) {
41: this .hostName = hostName;
42: this .port = port;
43: this .timeout = timeout;
44: this .checkInterval = checkInterval;
45: this .client = client;
46: }
47:
48: public final String getErrorText() {
49: return errorText;
50: }
51:
52: private final void setErrorText(String s) {
53: errorText = s;
54: }
55:
56: public Socket connect() {
57: socket = null;
58: long start = System.currentTimeMillis();
59: connectThread.start();
60: while (System.currentTimeMillis() - start < timeout) {
61: try {
62: connectThread.join(checkInterval);
63: } catch (InterruptedException e) {
64: Log.error(e);
65: setErrorText(e.toString());
66: return null;
67: }
68: if (client != null && client.cancelled()) {
69: Log.debug("cancelled!");
70: return null;
71: }
72: if (!connectThread.isAlive())
73: break;
74: }
75: if (socket == null && connectThread.isAlive())
76: setErrorText("Timed out");
77: return socket;
78: }
79:
80: private final Thread connectThread = new Thread("connect") {
81: public void run() {
82: try {
83: socket = new Socket(hostName, port);
84: } catch (NoRouteToHostException e) {
85: setErrorText("No route to host " + hostName);
86: } catch (UnknownHostException e) {
87: setErrorText("Unknown host " + hostName);
88: } catch (ConnectException e) {
89: setErrorText("Connection refused");
90: } catch (Exception e) {
91: Log.error(e);
92: setErrorText("Unable to connect to " + hostName);
93: }
94: }
95: };
96: }
|