I'm having some trouble with Java Sockets.
I have a pair of applications that establish a connection between them (one opens a ServerSocket
, calls accept()
and waits, and the other connects via the Socket(InetAddress,int)
constructor.
After the socket connection is established, a Thread
is created with this Runnable
.
public void run() {
System.out.print("Watching Socket for closing ");
while(running) {
if(socket.isClosed()) {
System.out.println("Socket has been closed");
break;
}
}
this.running = false;
//safely ends this application by closing i/o and exiting.
}
My problem is that when one of the applications is closed unexpectedly (in my case terminated from Eclipse) calling Socket.isClosed()
still shows the socket is open, and so the loop keeps running as if the Socket was open.
How can I detect when the Socket is closed when the Java application on the other side is forcibly ended?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…