0

I'm trying to create a server that can detect when a client disconnects. I searched online and found this method isReachable() that from what I understand should be perfect for this. The problem is I tried to test it, but it doesn't work to detect disconnection, it always returns true even after I close the program on the different PC I'm using as a client.

public static void main(String[] args) {
    int socketPort = 80;

    ServerSocket socket;
    try {
        socket = new ServerSocket(socketPort);
    } catch (IOException e) {
        System.out.println("Impossible to open server socket");
        System.exit(1);
        return;
    }

    while (true) {
        try {
            Socket client = socket.accept();
            while (true) {
                if (client.getInetAddress ().isReachable (60 * 1000)==true)
                    System.out.println ("still connected");
                else
                    System.out.println ("disconnected");
            }

        } catch (IOException e) {
            System.out.println("Connection Lost");
        }
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • chances are, it is just testing whether or not it can reach that other computer on the network, he's not testing whether ornot the application is running – Stultuske Jun 09 '22 at 10:58
  • 3
    "*A typical implementation [of isReachable] will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.*" https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#isReachable(int) i.e. it doesn't matter whether the application is running, just that the machine itself is – Michael Jun 09 '22 at 11:00
  • Why do you think calling `isReachable()` on an `InetAddress` object would tell you whether or not a socket connection is still open? – Mark Rotteveel Jun 09 '22 at 11:30

0 Answers0