gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:13:57 29 4
gpt4 key购买 nike

我在服务器端遇到问题,当我故意拔掉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 android时,该方法被搁置。

最佳答案

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

如果您不打算迭代,为什么要使用 while 循环?

关于java - 如何发现客户端android套接字断开连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055224/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com