急,急,TCP连接时服务器端Down掉为什么客户端不抛出异常?内有代码!
在TCP建立连接之后我把Server关掉,Client在Sleep一段时间之后认为连接还没有断,请问如何设置Client的参数使得Client端可以捕捉到Server端Down掉的异常或状态,谢谢!
import java.io.*;
import java.net.*;
public class TCPServer
{
public TCPServer()
{
try
{
server = new ServerSocket(5000);
} catch (Exception e)
{
System.out.println(e);
}
while(true)
{
System.out.println("Listening for connection ...");
try
{
Socket socket = server.accept();
System.out.println("Connect From "+ socket.getInetAddress().getHostAddress()+":"+socket.getPort());
socket.close();
} catch (Exception e)
{
System.out.println(e);
}
}
}
public static void main(String[] args)
{
TCPServer TCPServer1 = new TCPServer();
}
ServerSocket server = null;
}
import java.io.*;
import java.net.*;
public class TCPClient
{
public TCPClient()
{
try
{
System.out.println("Attemping to connect to a TCP Server ...");
Socket socket = new Socket("127.0.0.1", 5000);
socket.setSoTimeout(1000);
socket.setKeepAlive(true);
System.out.println("Connection established ! Port "+socket.getLocalPort());
try
{
Thread.sleep(50000);
} catch (Exception e) {}
System.out.println("isConnected: "+socket.isConnected()); // Server已经Down掉但是仍然打印true
socket.close();
} catch (Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
TCPClient TCPClient1 = new TCPClient();
}
}