0

我尝试使用读取超时来克服服务器端的用户断开连接检测。这是我的代码的一部分:

try {
        socket.setSoTimeout(3000);
        in = new DataInputStream(socket.getInputStream());
        out = new DataOutputStream(socket.getOutputStream());
        usr = new User(in.readUTF());
        usr.connectUser();
        int i=0;
        while(true){
            try{
                i = in.readInt();
            }
            catch(SocketTimeoutException e){
                System.Out.Println("Timeout");
                // user connected, no data received
            }
            catch(EOFException e){
                System.Out.Println("Disconnected");
                // user disconnected
            }
        }
    }
    catch(Exception  e){
        // other exceptions
    }

该代码工作正常,除了“用户断开连接”问题。我想捕获超时异常并继续等待数据,但前提是客户端仍然连接。为什么除了 SocketTimeoutException 我从来没有遇到过其他异常?我不应该在 in.readInt() 因为客户端断开连接而无法使用套接字时得到 IOException 吗?

有没有其他简单的方法来检测用户断开连接?我的意思是不必要的断开连接,例如用户突然关闭wifi等...

谢谢,利奥兹。

4

1 回答 1

0

If the client didn't write anything within the timeout period, you get a SocketTimeoutException. If he disconnected instead of writing anything, you get an EOFException. Catch them separately. If you didn't get an EOFException, he didn't disconnect.

于 2012-11-03T21:54:14.750 回答