Thiago Trindade
Thiago Trindade

Reputation: 26

Socket.read() return nothing and doesn't throw exception when closed in Android

I have a Android code that send and receive data from a TCP socket. It works fine, but, when the socket is suddenly closed (disconnection from wi-fi, for example), i don't get any error, both for reading and for writing. In some devices, An exception is thrown in read thread, but in other devices (Note 4) no exception is thrown, and the app can't detect wheter the socket is closed or not.

The write code is bellow

try {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    writer.write(msg);
    writer.flush();
}catch (IOException e){
    e.printStackTrace();
}

The read Thread:

try {

    int bytesRead;
    String print = new String();
    print = "";
    InputStream is = socket.getInputStream();

    while (socket.isConnected()) {
        bytesRead = is.read();
        if (bytesRead != -1) {
            print += (char) bytesRead;
            if (bytesRead == ']') {
                final String toprint = new String(print);
                try{
                ((socketListener) Ui).onSocketListen(ip,toprint);
                }catch(NullPointerException ex){

                }
                print = "";
            }
        } else {
            socket.close();
            socket = new Socket();
            break;
        }

    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    socket = new Socket();
    e.printStackTrace();
} catch (Exception e){
    e.printStackTrace();
}

Upvotes: 0

Views: 501

Answers (1)

user207421
user207421

Reputation: 310909

the app can't detect wheter the socket is closed or not

The socket isn't closed. The connection is temporarily interrupted, but TCP is designed to survive that. Unless you have pending sends you won't detect a network interruption.

You can set a read timeout with Socket.setSoTimeout(), and when you catch the resulting SocketTimeoutException make a decision somehow on whether you're going to try again or give up.

Upvotes: 1

Related Questions