Skywalker
Skywalker

Reputation: 105

How to discover the client android socket disconnected?

I have a problem on the server side, when I unplug the android wifi purposely the server can not detect that the communication is over.

When closing the application server finds.

/**
 * Method Responsible for receiving last message from client socket.
 *
 * @return
 * @throws java.io.IOException
 */
public String receive() throws IOException {
    //receiver is a Scanner -> receiver = new Scanner(socket.getInputStream());
    while (receiver.hasNextLine()) {
     return receiver.nextLine();
     }
     return null;
}

@Override
public void run() {
    //loop waiting for the client message
    while (true) {
        String response;
        //receive message
        try {
            response = receive();
            //if the message come null means that the client disconnected
            if (response == null) {
                break;
            }
        } catch (Exception e) {
            break;
        }
        //mount message.
        Message msg;
        try {
            msg = new Gson().fromJson(response, Message.class);
        } catch (Exception e) {
            continue;
        }
        //manage message in new thread
        new Thread(new Runnable() {
            @Override
            public void run() {
                manageMessage(msg);
            }
        }).start();
    }
    close();
}

The receive() method always returns null when the client disconnects, but when I turn off the wifi android, the method is put on hold.

Upvotes: 0

Views: 401

Answers (1)

user207421
user207421

Reputation: 310875

Set a read timeout of suitable length on the socket, and catch SocketTimeoutException.

Why the while loop, if you're not going to iterate?

Upvotes: 1

Related Questions