我正在使用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!");
}
答案 0 :(得分:0)
尝试使用此
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), timeout);
文档显示:
SocketTimeoutException
- 如果超时在连接之前到期