如何发现客户端android套接字断开连接?

时间:2015-08-17 16:22:26

标签: java android sockets

我在服务器端遇到问题,当我故意拔掉android wifi时,服务器无法检测到通信结束了。

关闭应用程序服务器时找到。

/**
 * 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();
}

当客户端断开连接时,receive()方法总是返回null,但是当我关闭wifi安卓时,该方法被搁置。

1 个答案:

答案 0 :(得分:1)

在套接字上设置适当长度的读取超时,并捕获SocketTimeoutException

为什么while循环,如果你不打算迭代?