I am having a problem where the call to, sock.setSoTimeout(1000*15), works great if a host accepts the connect,
but then doesn't respond quickly enough, and I get a 'Read timed out', exception. However, sometimes the host is
not reachable over the network, in which case the setSoTimeout has no effect, and I assume it is the OS that times
out the request. Is there a way to set the socket timeout to catch 'Connection timed out' exceptions?
The following program demonstrates the problem, where the first host responded to the connect but just sat there
not responding, and so the 15 second timeout worked. The second host is on the network, but doesn't respond to
connects and so it takes 3 minutes, 9 seconds to timeout. I am using Java 1.4.2_13
Thanks in advance.
Jeff
java TimeoutTest
Mar 08, 2010 08:40:43 Attempting to connect to localhost on port 8000.
Mar 08, 2010 08:40:58 Exception => Read timed out
Mar 08, 2010 08:40:58 Attempting to connect to vtest.com on port 25.
Mar 08, 2010 08:44:07 Exception => Connection timed out
import java.util.*;
import java.io.*;
import java.net.*;
import com.xxx.util.NetUtil;
public class TimeoutTest
{
private String timeoutHost = "localhost";
private String conExcepHost = "vtest.com";
private int timeoutHostPort = 8000;
private int conExcepHostPort = 25;
public void sendPage()
{
String handshake = null;
String host = null;
String record = "";
String ISO = "8859_1";
Socket sock = null;
Writer wtr = null;
InputStream raw = null;
int rc = 0;
int port = 0;
InputStream in = null;
handshake = "Send some data\n";
for (int cntr = 0; cntr < 2; cntr++)
{
if (cntr == 0)
{
host = timeoutHost;
port = timeoutHostPort;
}
else
{
host = conExcepHost;
port = conExcepHostPort;
}
try
{
NetUtil.netLog("Attempting to connect to "+host+" on port "+port+".");
sock = new Socket(host, port);
sock.setSoTimeout(1000*15);
wtr = new OutputStreamWriter(sock.getOutputStream(), ISO); /* Issue the secret */
wtr.write(handshake); /* handshake. */
wtr.flush();
raw = sock.getInputStream();
in = new BufferedInputStream(sock.getInputStream());
while (rc != -1)
{
rc = in.read();
record += (char)rc;
}
NetUtil.netLog("Response => "+record);
}
catch (IOException e)
{
NetUtil.netLog("Exception => "+e.getMessage());
}
}
}
public static void main(String[] args)
{
TimeoutTest tm = new TimeoutTest();
tm.sendPage();
}