0

I have a problem where there is no IOException thrown when a Telnet client disconnects.

I used the server code from the following source:

http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/Code/SocketThrdServer.java

From the given code, the server should terminate and display "Read Fail" when the client close. But it's not happening for Telnet or Putty (RAW connection). On the contrary, it works when I used the example Client given, it works perfectly.

I've also tried modifying the code so that readLine() doesn't block the I/O always, but using a timeout. However, it doesn't seem that it helped in detecting whether the Client has been disconnected.

    while (true) {
        try {
            client.setSoTimeout(1000);
            line = in.readLine();
            // Send data back to client
            out.println(line);
            textArea.append(line);

        } catch (SocketTimeoutException ex) {
            if(client.isClosed()) {
                System.out.println("Client disconnected");
                System.exit(-1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Read failed");
            System.exit(-1);
        }
    }

Is there something missing from using Telnet or Raw Connection?

Edit: In addition to that, when I run 2 Clients, and then I close the first client, there would be no exception thrown from BufferedReader...

4

1 回答 1

1

If it's a graceful shutdown, there should be no IO Exception. in.readLine(); should return null in that case, a case your code should handle.

于 2012-05-04T07:21:10.487 回答