The isConnected
method won't help, it will return true
even if the remote side has closed the socket. Try this:
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException
(broken pipe) will be thrown) on the associated Input/OutputStreams.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…