我正在尝试在 Android 应用程序中使用 TCP,因此有两个项目,一个是服务器,一个是客户端。 当我运行服务器并打开客户端时,一切正常并且消息正在传递到双方,尽管当我关闭应用程序(从模拟器)时,它不会在控制台中提醒我套接字连接已关闭并且尝试获取另一个连接,因此当尝试重新打开应用程序时,它不会重新连接,并且不会传递消息。
那么我到底做错了什么?我对 Android 和 TCP 很陌生,所以如果这是一个菜鸟问题,我很抱歉。
@Override
public void run() {
super.run();
running = true;
try {
System.out.println("S: Connecting...");
//create a server socket. A server socket waits for requests to come in over the network.
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
//create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
while (running) {
Socket client = serverSocket.accept();
try {
//sends the message to the client
mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
//read the message received from client
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//in this while we wait to receive messages from client (it's an infinite loop)
//this while it's like a listener for messages
while(!client.isClosed()) {
String message = in.readLine();
if (message != null && messageListener != null) {
//call the method messageReceived from ServerBoard class
messageListener.messageReceived(message);
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
最佳答案
更准确的说法是您没有正确测试断开连接。
-
当对等方断开连接时,
Socket.isClosed()
不会神奇地变为 true。所以用它来控制读循环是徒劳的。它仅告诉您您是否已关闭此套接字。readLine()
当对等点断开连接时返回 null,但您将其视为另一个值。
使用readLine()
的正确循环如下所示:
while ((line = in.readLine()) != null)
{
// ...
}
关于java - Android TCP - 应用程序关闭时套接字不会断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31868280/