Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

java - Detect Socket is closed after remote application is closed forcibly

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only way that socket.isClosed() return true is if you call yourself socket.close() as it is the only part where the boolean will be set to true.

What you could do is simply try to read from the socket using an inputStream and -1 will be returned if it is closed (if the end of stream has been reached).

See documentation for more information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...