我正在使用 java 套接字连接到我们的一个网络节点执行命令获取一些数据并显示在 html 网格中。问题是当节点不可用或由于网络问题而导致查询不会超时时应用程序性能严重下降。我尝试过 socket.sotimeout() 但它似乎不起作用。下面是供参考的代码。
public void initializeConnection(String host, int port)
throws IOException
{
try
{
if(debug)
System.out.println((new StringBuilder()).append("connecting to host ").append(host).append(" port: ").append(port).toString());
socket = new Socket(host, port);
socket.setSoTimeout(6000);
socket.setTcpNoDelay(true);
in = new BufferedInputStream(socket.getInputStream());
out = new BufferedOutputStream(socket.getOutputStream());
}
catch(IOException e)
{
System.out.println("Connection could not be established");
closeConnection();
throw e;
}
if(debug)
System.out.println("Connected!");
}