Go to the documentation of this file.00001
00002 import java.net.InetSocketAddress;
00003 import java.net.Socket;
00004
00005
00006
00007
00008
00009
00010
00011
00012 public class PortConnect extends Thread
00013 {
00014
00015
00016
00017
00018 public interface Context
00019 {
00020
00021
00022
00023 public abstract InetSocketAddress getNextSocketAddress ();
00024
00025
00026
00027
00028
00029 public abstract void onPortConnected( long threadId, InetSocketAddress addr,
00030 boolean ok, String error, int timeMillis );
00031
00032
00033
00034
00035 public abstract void workerThreadSignIn( long threadId );
00036
00037
00038
00039
00040 public abstract void workerThreadSignOut( long threadId );
00041 }
00042
00043
00044
00045
00046 private int timeoutMillis;
00047
00048
00049
00050
00051 private Context context;
00052
00053
00054
00055
00056
00057
00058
00059 public PortConnect( Context context, int timeoutMillis )
00060 {
00061 this.context = context;
00062 this.timeoutMillis = timeoutMillis;
00063 }
00064
00065
00066
00067
00068
00069
00070 public void reportConnectionStatus( InetSocketAddress endpoint )
00071 {
00072 boolean portStatus = false;
00073 String error = "Failed";
00074
00075
00076
00077 Socket socket = null;
00078 long startTime = System.nanoTime ();
00079
00080 try {
00081 socket = new Socket ();
00082 socket.connect( endpoint, timeoutMillis );
00083 error = "Connected";
00084 portStatus = true;
00085 } catch( Exception e ) {
00086
00087 error = e.toString ();
00088 }
00089
00090 if ( socket != null && ! socket.isClosed () ) {
00091 try {
00092 socket.close ();
00093 } catch( Exception e ) {
00094
00095 }
00096 }
00097
00098
00099
00100 this.context.onPortConnected(
00101 getId(), endpoint, portStatus, error,
00102 (int) ( ( System.nanoTime () - startTime ) / 1000000l ) );
00103 }
00104
00105
00106
00107
00108
00109
00110
00111 @Override
00112 public void run()
00113 {
00114 context.workerThreadSignIn( getId () );
00115
00116 while( true )
00117 {
00118 InetSocketAddress endpoint = context.getNextSocketAddress ();
00119
00120
00121
00122 if ( endpoint == null ) {
00123 break;
00124 }
00125
00126
00127
00128
00129 reportConnectionStatus( endpoint );
00130 }
00131
00132 context.workerThreadSignOut( getId () );
00133
00134
00135
00136 try {
00137 Thread.sleep( 365 * 86400 * 1000 );
00138 } catch( InterruptedException e ) {
00139
00140 }
00141 }
00142 }