1 package org.apache.jcs.auxiliary.lateral.socket.tcp.utils;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.net.Socket;
24
25 /***
26 * Socket openere that will timeout on the initial connect rather than block
27 * forever. Technique from core java II.
28 *
29 * @version $Id: SocketOpener.java 536904 2007-05-10 16:03:42Z tv $
30 */
31 public class SocketOpener
32 implements Runnable
33 {
34
35 private String host;
36
37 private int port;
38
39 private Socket socket;
40
41 /***
42 * Opens a socket with a connection timeout value. Joins against a backgroud
43 * thread that does the openeing.
44 *
45 * @param host
46 * @param port
47 * @param timeOut
48 * @return Socket
49 */
50 public static Socket openSocket( String host, int port, int timeOut )
51 {
52 SocketOpener opener = new SocketOpener( host, port );
53 Thread t = new Thread( opener );
54 t.start();
55 try
56 {
57 t.join( timeOut );
58 }
59 catch ( InterruptedException ire )
60 {
61
62 }
63 return opener.getSocket();
64 }
65
66 /***
67 * Constructor for the SocketOpener object
68 *
69 * @param host
70 * @param port
71 */
72 public SocketOpener( String host, int port )
73 {
74 this.socket = null;
75 this.host = host;
76 this.port = port;
77 }
78
79 /*** Main processing method for the SocketOpener object */
80 public void run()
81 {
82 try
83 {
84 socket = new Socket( host, port );
85 }
86 catch ( IOException ioe )
87 {
88
89 }
90 }
91
92 /***
93 *
94 * @return The opened socket
95 */
96 public Socket getSocket()
97 {
98 return socket;
99 }
100 }