【发布时间】:2012-08-22 08:12:20
【问题描述】:
我正在使用 Apache Commons TelnetClient 为某些交换机创建一个自动 telnet 接口。如果我直接从机器远程登录到交换机,连接似乎永远不会超时。随机地,在 Java 程序中,连接似乎与 InputStream 一起立即关闭。我试图建立一个检查来查看连接失败并尝试再次建立连接,但如果第一次失败,它总是失败。
import org.apache.commons.net.telnet.TelnetClient;
public String connect()
{
String errorMessage = null;
tcConnectionHandle = new TelnetClient();
tcConnectionHandle.setDefaultTimeout(iTimeOutMilliseconds);
try
{
tcConnectionHandle.connect(strConnectionIP, intConnectionPort);
osOutput = tcConnectionHandle.getOutputStream();
isInput = tcConnectionHandle.getInputStream();
int availableBytes = isInput.available();
while(availableBytes <= 0)
{
tcConnectionHandle = null;
isInput = null;
osOutput = null;
Thread.sleep(500);
tcConnectionHandle = new TelnetClient();
Thread.sleep(500);
tcConnectionHandle.setDefaultTimeout(iTimeOutMilliseconds);
Thread.sleep(500);
tcConnectionHandle.connect(strConnectionIP, intConnectionPort);
Thread.sleep(500);
osOutput = tcConnectionHandle.getOutputStream();
Thread.sleep(500);
isInput = tcConnectionHandle.getInputStream();
Thread.sleep(500);
availableBytes = isInput.available();
System.out.println("reopened: " + availableBytes);
}
}
catch(InterruptedException iX)
{
errorMessage = "Could not establish connection. " + iX.getLocalizedMessage();
}
catch(SocketException sX)
{
errorMessage = sX.getMessage();
}
catch(IOException ioX)
{
errorMessage = ioX.getMessage();
}
return errorMessage;
}
如果我省略了Thread.sleep(500),它将永远不会有任何可用字节。暂停后,结果为 20,但是,如果我尝试使用 isInput.read(),它将返回 -1,这意味着 InputStream 已关闭。
我正在寻找一种方法来捕获连接失败并再次尝试连接。它发生得太频繁了,不能再试一次。
【问题讨论】:
-
为什么要测试可用字节为负数或零?测试它有什么意义?谁说连接后必须立即有可用数据?读一读。它将阻塞直到数据到达。使用读取超时来控制它。
-
我正在做测试,因为读取失败并返回 -1(如下所述我的代码块)。由于 InputStream 已关闭,因此在数据到达之前它不会阻塞。
标签: java inputstream telnet